2015-04-02 63 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