Node.js console.log() in txt file

Limatuz picture Limatuz · Dec 20, 2016 · Viewed 69.4k times · Source

I have another question (last question). At the moment i am working on a Node.js project and in this I have many console.log() functions. This has worked okay so far but I also want everything that's written to the console to also be written in a log-file. Can someone please help me?

For example:

Console.log('The value of array position [5] is '+ array[5]);

In my real code its a bit more but this should give you an idea.

Thank you hopefully.

Answer

Charlie Martin picture Charlie Martin · Dec 20, 2016

Just run the script in your terminal like this...

node script-file.js > log-file.txt

This tells the shell to write the standard output of the command node script-file.js to your log file instead of the default, which is printing it to the console.

This is called redirection and its very powerful. Say you wanted to write all errors to a separate file...

node script-file.js >log-file.txt 2>error-file.txt

Now all console.log are written to log-file.txt and all console.error are written to error-file.txt