0

My simple script (test.js):

const x = 10;
console.log('Number X = ' + x);
throw new Error('emulating some error in the code');
console.log('Finish');

For example I start my script with command: node test.js >> log.txt

I can see error message only in console. Error isn't written in log.txt

How I can write error message in log.txt too?

Scott
  • 4,974
  • 6
  • 35
  • 62
  • If you just want to redirect the output in the shell, try with `node test.js >> log.txt 2>&1` That way you are redirecting `stderr` to `stdout` – fractalix Sep 05 '19 at 17:14

1 Answers1

0

This must be exactly what you are looking for:

// First part: Writing to 'log.txt' file
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('log.txt', { flags: 'a' });
  // Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;

console.log = function () {
  logFile.write(util.format.apply(null, arguments) + '\n');
  logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;

// Second part: creating function just to generate an error
function div (x, y, done) {
  if (y === 0)
    return done (Error ('Cannot divide by zero'))
  else
    return done (null, x / y)
}

div (6, 0, function (err, result) {
  // *always* check for err
  if (err)
    console.log ('error', err.message, err.stack)
  else
    console.log ('result', result)
})

First part of the code is for writing to 'log.txt' file, and second part is just for generating an error. Hope this is helpful :)

Scott
  • 4,974
  • 6
  • 35
  • 62