node.js 中将 console.log 日志内容输出到文件
async function Get_alldata ( ) {
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') // 输出 01、02、03 到文本文件;
process.stdout.write(util.format.apply(null, arguments) + '\n')
}
console.log( ' 01' );
console.log( ' 02' );
console.log( ' 03' );
****** other code ******
return await Get_alldata() ;
}
上面的代码,只能在 注屏蔽释掉 return await Get_alldata() ; 语句之后,在程序执行完之后,将 01、02、03 一次性的写入到到文本文件?
如果 不注屏蔽释掉 return await Get_alldata() ; 那么 01、02、03 根本就没有写入文本文件;
请问怎么实现 在直接使用 console.log( ) 函数的情况下,实时的将 console.log 输出的 01、02、03 写入到到文本文件?
我实现了 await console.log( ) 的办法,可是太复杂了,使用也不方便;
所以想请教一下这个社区的网友,有没有更好的办法?
附上两个参考文档: Node 中 console.log 的同步实现: https://blog.csdn.net/li420520/article/details/83420994
[Node.js 系统模块系列一] console 模块解读: https://juejin.im/post/5bf2b31f5188252e89668fe1
如果有可以使用的插件,希望能够帮忙给个插件配置文件,谢谢!