Readline输出到文件Node.js

时间:2015-04-02 10:14:51

标签: node.js outputstream

如何将输出写入文件?我试过而不是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);
});

2 个答案:

答案 0 :(得分:3)

参考node/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(),其定义在块之后。

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){})打开文件即可。

示例代码:

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);
});

答案 1 :(得分:1)

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

示例:

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}`);
});