node.js在运行时,有时需要将console.log的内容打印输出到文件来调试。可以用以下方法。

Linux中可以在启动添加:

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

也可以只输出错误到日志文件,>>代表追加模式。2代表错误输出:

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

在node.js中输出:

var fs      = require('fs')
var util    = require('util')

var logPath = 'upgrade.log'
var logFile = fs.createWriteStream(logPath, { flags: 'a' })

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

console.error = function() {
  logFile.write(util.format.apply(null, arguments) + '\n')
  process.stderr.write(util.format.apply(null, arguments) + '\n')
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐