0

I'm am capturing console.log data and saving it to a log file but I also want to show the data in the console. How can I do this? I'd rather not install a package just do this.

This is what I am using to capture the console.log data:

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);
Airerr
  • 451
  • 4
  • 16

1 Answers1

0

Please check out this answer.

So pretty much you can do it like this.

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');
Antonio Narkevich
  • 4,206
  • 18
  • 28