在 Debian 上遇到 JS 日志编码异常(比如中文变成乱码、问号、十六进制 \uXXXX、或终端显示异常),通常和 locale、文件编码、终端、Node/浏览器输出方式 有关。下面按常见场景给你排查与解决办法。
请先明确是哪一种:
\u4e2d\u6587locale
如果看到:
LANG=
LC_ALL=
或
C
就容易出现编码问题。
sudo apt update
sudo apt install locales
sudo dpkg-reconfigure locales
勾选:
en_US.UTF-8
zh_CN.UTF-8
设置默认:
sudo update-locale LANG=en_US.UTF-8
重启或重登录后确认:
echo $LANG
# 应为 en_US.UTF-8 或 zh_CN.UTF-8
Node 控制台输出依赖:
确保:
node -e "console.log('中文测试')"
正常显示。
错误方式:
fs.writeFileSync('log.txt', '中文')
推荐:
fs.writeFileSync('log.txt', '中文', 'utf8')
或:
const fs = require('fs')
fs.writeFile('log.txt', '中文', { encoding: 'utf8' }, () => {})
fs.readFile('log.txt', 'utf8', (err, data) => {
console.log(data)
})
如果你用:
请确认:
systemd 默认环境可能 没有 locale。
sudo systemctl edit your-js-service
加入:
[Service]
Environment=LANG=en_US.UTF-8
Environment=LC_ALL=en_US.UTF-8
重载:
sudo systemctl daemon-reload
sudo systemctl restart your-js-service
ENV LANG=C.UTF-8
ENV LC_ALL=C.UTF-8
docker run -e LANG=C.UTF-8 -e LC_ALL=C.UTF-8 your-image
\u4e2d\u6587这是 JSON 转义,不是乱码。
例如:
console.log(JSON.stringify({ msg: '中文' }))
解决:
console.log(JSON.stringify({ msg: '中文' }, null, 2))
或
console.log('中文')
locale 是 UTF-8utf8LANG如果你愿意,可以把: