如何在Node.js将console日志写入到文件

在node.js开发中,需要将日志重定向到文件,又不想用其他日志框架,查询node文档发现可以用如下方式简单实现:

javascript 复制代码
const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// 自定义日志对象
const logger = new Console({ stdout: output, stderr: errorOutput });
// 像console一样使用
const count = 5;
logger.log('count: %d', count);
// 在stdout.log输出: count 5 

参考:

控制台 | Node.js v18.18.2 文档

相关推荐
:-)3 小时前
macOS上管理多个Node.js版本
macos·node.js
夏子曦4 小时前
webpack 的工作流程
前端·webpack·node.js
thinkQuadratic20 小时前
使用node.js来实现SSE服务端向客户端推送消息
node.js
撸码到无法自拔2 天前
使用 MCP(模型上下文协议)和 Claude 在 Node.js 中构建聊天应用程序
node.js
Dontla2 天前
node.js模块化步骤(各标准区别)CommonJS规范、AMD规范、UMD规范、ES Modules (ESM)
node.js
正在努力Coding2 天前
Cannot find module ‘@npmcli/config‘
node.js
m0_zj2 天前
55.[前端开发-前端工程化]Day02-包管理工具npm等
前端·npm·node.js
zlpzlpzyd2 天前
node.js为什么产生?
node.js
大G哥2 天前
使用 MCP(模型上下文协议)和 Claude 在 Node.js 中构建聊天应用程序
node.js
小宋要上岸3 天前
通过 Node.js 搭配 Nodemailer 实现邮箱验证码发送
c++·node.js·nodemailer