2015-04-02 62 views
4

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

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

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

回答

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

非常感谢:) – noone 2015-04-02 22:14:48