Node.js console.log() in txt file

I would use a library instead of re-inventing the wheel. I looked for a log4j-type library on npm, and it came up with https://github.com/nomiddlename/log4js-node

if you want to log to the console and to a file:

var log4js = require('log4js');
log4js.configure({
  appenders: [
    { type: 'console' },
    { type: 'file', filename: 'logs/cheese.log', category: 'cheese' }
  ]
});

now your code can create a new logger with

var logger = log4js.getLogger('cheese'); 

and use the logger in your code

logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');

const fs = require('fs');
const myConsole = new console.Console(fs.createWriteStream('./output.txt'));
myConsole.log('hello world');

This will create an output file with all the output which can been triggered through console.log('hello world') inside the console.

This is the easiest way to convert the console.log() output into a text file.`


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