簡體   English   中英

nodejs:如何登錄到屏幕和文件?

[英]nodejs : how to log to screen AND to file?

  • 我在node.js中使用console.log:這樣我可以登錄到屏幕ex:

    節點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的答案tee命令:)

PS- console.log實際上在節點中所做的所有操作,以防萬一。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM