nodejs读取本地中文json文件出现乱码

本文介绍了在Node.js中读取包含中文的UTF-8 JSON文件时可能出现的乱码问题及其解决方案。首先,确认文件是否以UTF-8无BOM编码,因为Node.js不会自动去除BOM。可以使用NPM模块去除BOM或手动处理。其次,检查JSON格式是否有误,如缺少或多余的逗号。此外,注意Node.js代码文件本身应以UTF-8编码,否则可能在写入中文时产生乱码。在确保文件编码正确的情况下,直接以utf8格式读取文件即可。
摘要由CSDN通过智能技术生成

1. 确定json文件是UTF-8 无BOM编码的的。如果有BOM,会在读取第一行的时候出现乱码。

Per "fs.readFileSync(filename, 'utf8') doesn't strip BOM markers #1918"fs.readFile is working as designed: BOM is not stripped from the header of the UTF-8 file, if it exists. It at the discretion of the developer to handle this.

Possible workarounds:

What you are getting is the byte order mark header (BOM) of the UTF-8 file. When JSON.parse sees this, it gives an syntax error (read: "unexpected character" error). You must strip the byte order mark from the file before passing it to JSON.parse:

fs.readFile('./myconfig.json',
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值