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:
data = data.replace(/^\uFEFF/, '');
perhttps://github.com/joyent/node/issues/1918#issuecomment-2480359- Transform the incoming stream to remove the BOM header with the NPM module
bomstrip
perhttps://github.com/joyent/node/issues/1918#issuecomment-38491548
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',