在 Node.js 中遇到日志乱码,通常是字符编码不一致导致的,尤其是在 Windows 终端 或 文件日志 中比较常见。下面按常见场景给你总结解决方案。
原因
Windows 终端默认编码是 GBK,而 Node.js 输出是 UTF-8。
chcp 65001
然后重新运行:
node app.js
注意:CMD 对 UTF-8 支持一般,推荐用 PowerShell / Windows Terminal
$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
process.stdout.setDefaultEncoding('utf8');
console.log('中文日志');
错误示例
fs.writeFileSync('app.log', '中文日志');
正确写法
fs.writeFileSync('app.log', '中文日志', 'utf8');
✅ 写文件一定要指定编码
fs.readFileSync('data.txt', 'utf8');
或:
fs.createReadStream('data.txt', { encoding: 'utf8' });
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('中文日志');
如果是 JSON:
res.setHeader('Content-Type', 'application/json; charset=utf-8');
✅ 日志文件一定要 UTF-8
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.File({
filename: 'app.log',
options: { encoding: 'utf8' }
})
]
});
| 场景 | 是否 UTF-8 |
|---|---|
| Node.js 源码 | ✅ UTF-8 |
| 终端编码 | ✅ UTF-8 |
| 写文件 | ✅ 指定 utf8 |
| HTTP 响应 | ✅ charset=utf-8 |
| 日志库 | ✅ 配置文件编码 |
Node.js + Windows Terminal + UTF-8
基本可以彻底解决乱码问题。
如果你愿意,可以告诉我:
我可以给你一个完全针对性的解决方案。