Linux nodejs:如何登录到屏幕和文件?
我在node.js中使用console.log:这样我可以登录到屏幕 例: 节点myscript.js 如果我使用Linux nodejs:如何登录到屏幕和文件?,linux,node.js,Linux,Node.js,我在node.js中使用console.log:这样我可以登录到屏幕 例: 节点myscript.js 如果我使用 节点myscript.js>log.txt然后我登录到文件log.txt 如何登录到屏幕和文件?如果您希望此行为在应用程序中持续存在,您可以创建一个直通流,并将其传输到writeStream和stdout var util = require('util'); var fs = require('fs'); // Use the 'a' flag to append to th
节点myscript.js>log.txt
然后我登录到文件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(终端显示)和日志文件
您还可以通过流省略,只需在monkey patched函数中写入两个流
console.log = function () {
var text = util.format.apply(this, arguments) + '\n';
ws.write(text);
process.stdout.write(text);
};
直通流只给你一个单一的流,你可以在你的应用程序周围以其他方式利用它,你总是知道它是通过管道传输到两个输出流的。但是,如果您只想使用monkey patchconsole.log
,那么后面的示例就足够了:)
如果您只想从终端单次运行应用程序,请参阅和tee
命令:)
PS-是console.log
在节点中实际执行的所有操作,以防您感到奇怪
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
如果你想让这种行为在你的应用程序中持久化,你可以创建一个直通流,并通过管道将其传输到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(终端显示)和日志文件
您还可以通过
流省略,只需在monkey patched函数中写入两个流
console.log = function () {
var text = util.format.apply(this, arguments) + '\n';
ws.write(text);
process.stdout.write(text);
};
直通流只给你一个单一的流,你可以在你的应用程序周围以其他方式利用它,你总是知道它是通过管道传输到两个输出流的。但是,如果您只想使用monkey patchconsole.log
,那么后面的示例就足够了:)
如果您只想从终端单次运行应用程序,请参阅和tee
命令:)
PS-是console.log
在节点中实际执行的所有操作,以防您感到奇怪
Console.prototype.log = function() {
this._stdout.write(util.format.apply(this, arguments) + '\n');
};
使用tee
node myscript.js | tee log.txt
使用tee
node myscript.js | tee log.txt