输出到控制台和日志文件

时间:2017-10-12 02:48:48

标签: node.js fs

我正在捕获console.log数据并将其保存到日志文件中,但我还想在控制台中显示数据。我怎样才能做到这一点?我不想安装包只是这样做。

这是我用来捕获console.log数据的原因:

var stdo = fs.createWriteStream('log.txt', {'flags': 'a'});
var write = function(write) {
  return function(string, encoding, fd) {
    stdo.write(string);
  };
};
process.stdout.write = write(process.stdout.write);

1 个答案:

答案 0 :(得分:0)

请查看this answer。

所以你可以这样做。

const fs = require('fs');

let outputFileStream = fs.createWriteStream('log.txt', {'flags': 'a'});

const originalWrite = process.stdout.write;

process.stdout.write = function() {
  originalWrite.apply(process.stdout, arguments);
  outputFileStream.write.apply(outputFileStream, arguments);
};

//These 3 lines go both to the file and to the console.
console.log('What is love');
console.log('Baby don\'t hurt me');
console.log('Don\'t hurt me');

//Won't get to the file. As it's a different stream.
console.error('No more');