inf3rno
inf3rno

Reputation: 26139

nodejs - pipe appjs console to a file

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.

Upvotes: 1

Views: 1517

Answers (1)

supernova
supernova

Reputation: 3883

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

Upvotes: 4

Related Questions