I've created:
var access = fs.createWriteStream('/var/log/node/api.access.log', { flags: 'w' });
Then piped:
process.stdout.pipe(access);
Then tried:
console.log("test");
And nothing has appeared in /var/log/node/api.access.log. However this way is working:
process.stdout.pipe(access).write('test');
Could someone explain what am I doing wrong ?
I solved this problem the following way:
Of course you can also separate stdout and stderr if you want.
I also would strongly recommend to handle uncaught exceptions:
This will cover the following situations:
process.stdout
is a Writable.pipe
is a method ofReadable
(Cf StreamAPI documentation : https://nodejs.org/api/stream.htmlYou can see the documentation of
process.stdout
here : https://nodejs.org/api/process.html#process_process_stdoutIt's surprising that you can do
process.stdout.pipe(...);
without any error. But i suppose this call just do nothing. Except returning a new Writable stream binded to stdout (or maybe it returnsprocess.stdout
itself. There's no specification for that in the documentation).If you want to redirect stdout to a file, you have many solutions :
node myfile.js > api.access.log
.process.stdout
with your own stream (and you can do whatever you want with this)@user3173842 for the reply on I solved this problem the following way:
you do understand that
process.stdout
continues afterprocess.on('exit')
and therefore thefs.WriteStream
closes after withprocess.stdout
, according to https://github.com/nodejs/node/issues/7606so now the question remains, if the developer desired to have the
fs.Writestream.write()
return to its normal functionality and whenfs.Writestream.end
is called the writestream closes. How would the developer go about doing this I didIt works and you use the once method because the
process.stdout
seems to do a lot of work at this time. Is this good practice, would you do this or what would you do in this situation anyone can feel free to reply.Checkout
console.Console
, the parent class of the normalconsole
.You can then you use
myConsole.log
,myConsole.error
,myConsole.dir
, etc. and write directly to your file.You can also monkey patch
process.stdout.write
as follows:there are also other options for overwriting
console._stdout
depending on the motivation for logging thestdout
to a file.