Ubuntu 下 Node.js 日志出现乱码,通常不是 Node.js 本身的问题,而是字符编码不一致导致的。下面按常见原因给你排查思路和解决办法。
locale
如果看到类似:
LANG=C
LC_ALL=
或不是 UTF-8,就很可能乱码。
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
编辑:
sudo nano /etc/default/locale
写入:
LANG=en_US.UTF-8
LC_ALL=en_US.UTF-8
然后重启或重新登录。
但终端不支持 UTF‑8就会乱码。
node -e "console.log(process.stdout.encoding)"
如果不是 utf8,说明终端有问题。
file -i app.log
如果看到:
app.log: text/plain; charset=iso-8859-1
说明不是 UTF‑8。
fs.writeFileSync('app.log', '中文日志', 'utf8');
iconv -f gbk -t utf8 app.log > app_utf8.log
如果你在 Windows 写代码 / 日志,再传到 Ubuntu:
console.log('中文');
iconv -f gbk -t utf8 main.js -o main_utf8.js
PM2 本身不乱码,但终端编码不对会乱。
✅ 解决:
pm2 logs --raw
或确保服务器 locale 是 UTF‑8。
Docker 容器默认可能没 UTF‑8。
ENV LANG=en_US.UTF-8
ENV LC_ALL=en_US.UTF-8
| 检查项 | 命令 |
|---|---|
| 系统编码 | locale |
| Node stdout 编码 | process.stdout.encoding |
| 日志文件编码 | file -i app.log |
| 是否 Windows → Linux | iconv |
Ubuntu + Node.js 日志乱码 = 系统或终端不是 UTF‑8
如果你愿意,可以把下面信息发我,我可以精准定位:
我可以直接给你“改哪一行就解决”的方案。