Readline 输出到文件 Node.js [英] Readline output to file Node.js

查看:60
本文介绍了Readline 输出到文件 Node.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将输出写入文件?我尝试代替 process.stdout 使用 fs.createWriteStream(temp + '/export2.json'),但它不起作用.

How can I write output to file? I tried instead of process.stdout use fs.createWriteStream(temp + '/export2.json'), but it's not working.

var rl = readline.createInterface({
    input: fs.createReadStream(temp + '/export.json'),
    output: process.stdout,
    terminal: false
});

rl.on('line', function(line) {
    rl.write(line);
});

推荐答案

参考 节点/readline

第 313 行:

Interface.prototype.write = function(d, key) {
    if (this.paused) this.resume();
    this.terminal ? this._ttyWrite(d, key) : this._normalWrite(d);
};

通过调用 rl.write(),您可以写入 tty 或调用 _normalWrite(),其定义在块之后.

by calling rl.write() you either write to tty or call _normalWrite() whose definition follows the block.

Interface.prototype._normalWrite = function(b) {
  // some code 
  // .......

  if (newPartContainsEnding) {
    this._sawReturn = /\r$/.test(string);
    // got one or more newlines; process into "line" events
    var lines = string.split(lineEnding);
    // either '' or (concievably) the unfinished portion of the next line
    string = lines.pop();
    this._line_buffer = string;
    lines.forEach(function(line) {
      this._onLine(line);
    }, this);
  } else if (string) {
    // no newlines this time, save what we have for next time
    this._line_buffer = string;
  }
};

输出写入_line_buffer.

第96行:

 function onend() {
    if (util.isString(self._line_buffer) && self._line_buffer.length > 0) {
      self.emit('line', self._line_buffer);
    }
    self.close();
 }

我们发现,_line_buffer 最终会被发送到 line 事件.这就是您不能将输出写入 writeStream 的原因.为了解决这个问题,你可以简单地使用 fs.openSync()fs.write()rl.on('line',function(line){}) 回调.

We find, _line_buffer is emitted to line event eventually. That's why you cannot write output to writeStream. To solve this problem, you can simply open a file using fs.openSync(), and fs.write() in rl.on('line', function(line){}) callback.

示例代码:

var rl = readline.createInterface({
    input: fs.createReadStream(temp + '/export.json'),
    output: process.stdout,
    terminal: false
});

fd = fs.openSync('filename', 'w');
rl.on('line', function(line) {
    fs.write(fd, line);
});

这篇关于Readline 输出到文件 Node.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆