繁体   English   中英

Readline 输出到文件 Node.js

[英]Readline output to file 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);
});

参考节点/阅读线

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

readline不会使用 with 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}`);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM