Readline输出到文件Node.js

noo*_*one 6 outputstream node.js

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

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

rl.on('line', function(line) {
    rl.write(line);
});
Run Code Online (Sandbox Code Playgroud)

ozm*_*ozm 8

readline不使用 withoutput选项写入文件。但是,您可以照常创建写入流并照常写入。

例子:

const { EOL } = require("os");
const rl = readline.createInterface({
    input: fs.createReadStream(temp + '/export.json'),
});

const writeStream = fs.createWriteStream(temp + '/export2.json', { encoding: "utf8" })

rl.on('line', function(line) {
    writeStream.write(`${line}${EOL}`);
});
Run Code Online (Sandbox Code Playgroud)


小智 5

参考节点/阅读线

第313行:

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

通过调用rl.write()您写入 tty 或调用_normalWrite()其定义遵循块。

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

输出写入_line_buffer.

第96行?

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

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

示例代码:

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);
});
Run Code Online (Sandbox Code Playgroud)