我用的console.log在我的Node.js:這樣我可以記錄到屏幕 例如:nodejs:如何登錄屏幕和文件?
節點myscript.js
如果我使用 node myscript.js>log.txt
然後我登錄到文件log.txt
如何登錄屏幕和文件?
我用的console.log在我的Node.js:這樣我可以記錄到屏幕 例如:nodejs:如何登錄屏幕和文件?
節點myscript.js
如果我使用 node myscript.js>log.txt
然後我登錄到文件log.txt
如何登錄屏幕和文件?
使用tee
。
node myscript.js | tee log.txt
如果您希望此行爲在您的應用程序中保持不變,則可以創建一個直通流並將其傳輸到writeStream和stdout。
var util = require('util');
var fs = require('fs');
// Use the 'a' flag to append to the file instead of overwrite it.
var ws = fs.createWriteStream('/path/to/log', {flags: 'a'});
var through = require('through2');
// Create through stream.
var t = new through();
// Pipe its data to both stdout and our file write stream.
t.pipe(process.stdout);
t.pipe(ws);
// Monkey patch the console.log function to write to our through
// stream instead of stdout like default.
console.log = function() {
t.write(util.format.apply(this, arguments) + '\n');
};
現在這將寫入stdout(終端顯示)和您的日誌文件。
您也可以省略through
流,只是寫在猴子打補丁函數兩個流。
console.log = function() {
var text = util.format.apply(this, arguments) + '\n';
ws.write(text);
process.stdout.write(text);
};
通流只是給你一個單一的數據流,你可以在你的周圍應用其他方式利用和你永遠知道它是通過管道輸送到兩個輸出流。但是,如果你想要的是猴子補丁console.log
那麼後者的例子是足夠的:)
如果你只是想爲你的應用程序從終端的單次運行爲此,請參閱@andars' answer和tee
命令:)
PS - This是所有console.log
實際上在節點中做的,以防萬一您想知道。
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};