nodejs:如何登录屏幕和文件?

yar*_*rek 1 linux node.js

  • 我在node.js中使用console.log:这样我可以登录到屏幕ex:

    node myscript.js

如果我使用, node myscript.js>log.txt那么我登录到文件log.txt

如何登录屏幕和文件?

and*_*ars 7

使用tee.

node myscript.js | tee log.txt
Run Code Online (Sandbox Code Playgroud)


Che*_*hev 5

如果您希望此行为在您的应用程序中持续存在,您可以创建一个直通流并将其通过管道传输到 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');
};
Run Code Online (Sandbox Code Playgroud)

现在这将写入标准输出(终端显示)和您的日志文件。

您也可以省略through流,只在猴子补丁函数中写入两个流。

console.log = function () {
  var text = util.format.apply(this, arguments) + '\n';
  ws.write(text);
  process.stdout.write(text);
};
Run Code Online (Sandbox Code Playgroud)

通过流只为您提供一个流,您可以在应用程序周围以其他方式使用它,并且您总是知道它已通过管道传输到两个输出流。但是如果你想要的只是猴子补丁,console.log那么后一个例子就足够了:)

如果您只想从终端对您的应用程序进行一次运行,请参阅@andars 的回答tee命令:)

PS -如果您想知道,就是console.log节点中实际执行的所有操作。

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + '\n');
};
Run Code Online (Sandbox Code Playgroud)