“位置0的JSON中的意外标记”?

我正在写一个node.js模块,它导入一个JSON文件:

const distDirPath = "c:/temp/dist/"; const targetPagePath = "c:/temp/index.html"; const cliJsonPath = "C:/CODE/MyApp/.angular-cli.json"; const fs = require('fs'); function deployAot() { var version = JSON.parse(fs.readFileSync(cliJsonPath, 'utf8')).version; } // export the module module.exports = { DeployAot: deployAot }; 

我在https://jsonlint.com/validation了上面的json文件的内容,它是有效的json,但是当我执行节点模块时,deployAot()中的第一行代码返回以下错误:

 "Unexpected token in JSON at position 0" 

以下是具体的json:

https://jsonblob.com/cd6753d2-9e51-11e7-aa97-2f95b001b178

有什么想法可能在这里?

由于@cartant已经在这个问题的评论中提到过,所以很可能你会在文件的开头得到一个特殊的字符(字节顺序标记)。

我会尽力取代这一点

 fs.readFileSync(cliJsonPath, 'utf8') 

有了这个

 fs.readFileSync(cliJsonPath, 'utf8').substring(1) 

摆脱string中的第一个字符,并会看到会发生什么。


GitHub问题fs.readFileSync(文件名'utf8')不会去除BOM标记

从这个问题的build议:

解决方法:

body = body.replace(/^\uFEFF/, '');

在读取UTF8文件后,您不确定是否可能有BOM标记。