如何在NodeJS(Linux)中写入日志文件?

时间:2019-09-05 17:02:58

标签: node.js linux debian

我的简单脚本(test.js):

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

例如,我使用以下命令启动脚本: node test.js >> log.txt

我只能在控制台中看到错误消息。错误未写入log.txt

我如何也可以在log.txt中写入错误消息?

1 个答案:

答案 0 :(得分:0)

这必须正是您要寻找的内容:

// 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)
})

代码的第一部分用于写入'log.txt'文件,第二部分仅用于生成错误。希望这会有所帮助:)