在 Debian 上 Node.js 日志出现乱码,通常不是 Node.js 本身的问题,而是字符编码、终端环境或系统 locale 配置不一致导致的。下面按常见原因给你一个排查清单。
locale
如果看到类似:
LANG=
LC_ALL=
或
LANG=C
就说明 没有正确设置 UTF-8 locale。
locale -a | grep utf8
如果看不到 en_US.utf8 或 zh_CN.utf8,需要先生成。
sudo dpkg-reconfigure locales
勾选:
en_US.UTF-8zh_CN.UTF-8然后执行:
sudo update-locale LANG=en_US.UTF-8
重启或重新登录。
echo $LANG
应为:
en_US.UTF-8
✅ 此时 Node.js 的 console.log 中文通常就正常了。
Node.js:
console.log(process.stdout.encoding);
如果不是 utf8,说明终端或启动环境有问题。
Debian 基础镜像 默认没有 locale
ENV LANG=en_US.UTF-8
ENV LC_ALL=en_US.UTF-8
或:
RUN apt-get update && apt-get install -y locales \
&& sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen \
&& locale-gen
systemd 不会继承用户 shell 的 locale
在 service 文件中加:
[Service]
Environment=LANG=en_US.UTF-8
Environment=LC_ALL=en_US.UTF-8
然后:
sudo systemctl daemon-reexec
sudo systemctl restart your-service
本地终端编码 ≠ 服务器编码
确保:
LANG 是 UTF-8node app.js > app.log
查看文件编码:
file app.log
如果是 ISO-8859 或 unknown,说明写入时编码不对。
✅ 解决:
LANG=en_US.UTF-8 node app.js > app.log
tail / cat 看乱码可能是:
用:
iconv -f gbk -t utf8 app.log
PM2 不会自动继承 shell 的 locale
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
pm2 restart all
或:
pm2 start app.js --env LANG=en_US.UTF-8
| 检查项 | 命令 |
|---|---|
| 当前 locale | locale |
| 是否 UTF-8 | echo $LANG |
| Node stdout 编码 | process.stdout.encoding |
| 是否 Docker | 看 Dockerfile |
| 是否 systemd | 看 service 文件 |
| 是否 PM2 | pm2 env |
Debian 上 Node.js 日志乱码,99% 是因为系统 locale 不是 UTF-8,而不是 Node.js 的问题。
如果你愿意,可以把下面信息发我,我可以精准定位:
我可以直接给你“最小修复方案”。