node.js中将console.log日志内容输出到文件

栏目: Node.js · 发布时间: 7年前

内容简介:node.js在运行时,有时需要将console.log的内容打印输出到文件来调试。可以用以下方法。Linux中可以在启动添加:也可以只输出错误到日志文件,>>代表追加模式。2代表错误输出:

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming the Mobile Web

Programming the Mobile Web

Maximiliano Firtman / O'Reilly Media / 2010-07-23 / $44.99

* Learn how to use your existing skills to move into mobile web development * Discover the new possibilities of mobile web development, and understand its limitations * Get detailed coverage of ......一起来看看 《Programming the Mobile Web》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具