1

I try to pipe appjs console to a file with this code:

var fs = require('fs');
var logStream = fs.createWriteStream(__dirname+ '/log.txt', { flags: 'a' });
process.stdout.pipe(logStream);
process.stderr.pipe(logStream);
console.log("test");

It creates an empty file, but nothing more... With node.exe the "test" goes into the console, not into the log file. The platform is win32, but I don't think it counts.

What's the problem with the code?

conclusion:

Stdout, stderr and a file write stream are all sink type endpoints, so I cannot bind them together. I need to replace stdout and stderr with douplex mock streams so I will be able to bind these mock streams both to the original sinks and the log sink. I am not sure whether console.log and console.error will be affected by replacing the streams with the mechanism supernova suggested, I'd rather use a dedicated logger, which uses the console instead of this workaround.

inf3rno
  • 24,976
  • 11
  • 115
  • 197

1 Answers1

4

you have to define getters for process.stdin, process.stdout and process.stderr

var fs = require("fs")
  , errlog = fs.createWriteStream("./err.log", { flags: 'a' })

process.__defineGetter__("stderr", function(){
  return errlog 
})

process.stderr.write("test")

this should work

supernova
  • 3,814
  • 3
  • 22
  • 37
  • It works for `process.stderr.write("test")`, but doesn't work for `console.log('test')`. Can you tell me why so? and How can I fix this? – Salman Sep 02 '13 at 10:14
  • console.log() goes to STDOUT, not to STDERR. I cannot add this code to my node app, telling me : TS2339: Property '__defineGetter__' does not exist on type 'Process'. – ante.sabo Oct 23 '20 at 16:14