npm install无法读取package.json

Cei*_*ish 10 package-managers npm

我正在尝试管理我的节点包依赖项.我希望能够通过运行命令来安装所有必需的依赖项,从我所读到的,实现此目的的一种方法是使用package.json文件并运行npm install.所以我的JSON文件看起来像这样:

{
 "name": "Name-Of-The-Thing",
 "description": "The Thing's Name",
 "author": "The Dude <the.dude@dudethinking.com>",
 "dependencies": {
      "mocha":">= 1.12.0",
      "mocha-phantomjs":">= 3.1.0",
      "chai":">= 1.7.2",
      "phantomjs":">= 1.9.1"
 }
}
Run Code Online (Sandbox Code Playgroud)

但是npm install报告以下错误:

npm ERR! Failed to parse json
npm ERR! Unexpected token ?
npm ERR! File: C:\Path\To\The\Thing\package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "test"
npm ERR! cwd C:\Path\To\The\Thing
npm ERR! node -v v0.8.15
npm ERR! npm -v 1.1.66
npm ERR! file C:\Path\To\The\Thing\package.json
npm ERR! code EJSONPARSE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Path\To\The\Thing\npm-debug.log
npm ERR! not ok code 0
Run Code Online (Sandbox Code Playgroud)

谁知道为什么?

Myr*_*tol 13

正确答案:

您的编辑器向JSON文件添加了一个字节顺序标记,这使得八位字节流成为无效的JSON文本.

JSON RFC说:

JSON文本应以Unicode编码.默认编码为UTF-8.

由于JSON文本的前两个字符将始终为ASCII字符[RFC0020],因此可以确定八位字节流是UTF-8,UTF-16(BE或LE)还是UTF-32(BE或LE)通过查看前四个八位字节中的空值模式.

       00 00 00 xx  UTF-32BE
       00 xx 00 xx  UTF-16BE
       xx 00 00 00  UTF-32LE
       xx 00 xx 00  UTF-16LE
       xx xx xx xx  UTF-8
Run Code Online (Sandbox Code Playgroud)

您提到的错误报告已因此原因而关闭.

根据我的理解,任何有效的ASCII编码文本也恰好是有效的UTF-8,因此在没有BOM的情况下,它解释了为什么它现在按预期工作.

一般来说,我认为您应该设置文本编辑器以UTF-8格式保存文件,而不使用字节顺序标记.看看没有BOM的UTF-8和UTF-8有什么不​​同?讨论.每个Node.js源代码的编码是什么?,Node.js将接受以这种方式编码的JS源文件中的非ASCII字符.当您想在源代码中的某处嵌入非ASCII字符串时,这可能很方便.