Node.js 日志打印乱码通常不是 Node.js 本身的问题,而是字符编码不一致导致的。下面按常见场景给你一个排查清单和解决方案。
Windows 默认可能不是 UTF‑8。
解决方法:
chcp 65001
然后重新运行:
node app.js
✅ 推荐:使用 Windows Terminal / PowerShell 7 / VS Code 终端
如果你把日志写入文件:
fs.writeFileSync('log.txt', '中文日志');
但用 Notepad / 某些编辑器 打开,可能显示乱码。
✅ 解决:
如果你的 .js 文件是:
Node.js 会按 UTF‑8 解析,导致乱码。
✅ 解决:
console.log('中文日志');
✅ Node.js 默认使用 UTF‑8 ❌ 乱码通常是终端或管道的问题
如果你用:
child_process.spawn('xxx')
npm install iconv-lite
const { spawn } = require('child_process');
const iconv = require('iconv-lite');
const child = spawn('cmd', ['/c', 'chcp 65001 && echo 中文']);
child.stdout.on('data', (data) => {
console.log(iconv.decode(data, 'cp936')); // GBK 转 UTF-8
});
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('中文');
或:
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
| 检查项 | 是否 |
|---|---|
| Node.js 文件是 UTF‑8 | ✅ |
| 终端支持 UTF‑8 | ✅ |
| 日志文件是 UTF‑8 | ✅ |
| 子进程输出编码正确 | ✅ |
| HTTP 响应头有 charset | ✅ |
Node.js 日志乱码 99% 是“输出环境编码 ≠ UTF‑8”导致的,而不是 Node.js 本身。
如果你愿意,可以把:
贴出来,我可以精准定位是哪一步导致的乱码。