nodejs:如何login屏幕和文件?
-
我在我的node.js中使用console.log:这样我可以login到屏幕前:
节点myscript.js
如果我使用node myscript.js>log.txt
然后我login到文件log.txt
我如何login屏幕和文件?
使用tee
。
node myscript.js | tee log.txt
如果你希望这个行为在你的应用程序中保持不变,你可以创build一个直通stream,并将其传递给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'); };
现在这将写入标准输出(terminal显示)和您的日志文件。
您也可以省略through
stream,只需在猴子补丁函数中写入两个stream。
console.log = function () { var text = util.format.apply(this, arguments) + '\n'; ws.write(text); process.stdout.write(text); };
直通stream只是给你一个单一的stream,你可以利用其他方式在你的应用程序周围,你总是知道,它是pipe道输出stream。 但是,如果你想要的只是猴子补丁console.log
那么后面的例子就足够了:)
如果您只希望从terminal执行一次应用程序,请参阅@andars'answer和tee
命令:)
PS – 这就是所有的console.log
实际上在节点中,以防万一你想知道。
Console.prototype.log = function() { this._stdout.write(util.format.apply(this, arguments) + '\n'); };