我刚刚通过nodejs.org上的包安装了node和npm,每当我尝试使用npm搜索或安装某个东西时,它会抛出以下错误,除非我执行命令。我觉得这是权限问题?我已经是管理员了。

npm ERR! Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json'
npm ERR!  { [Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/Users/chietala/.npm/-/all/.cache.json' }
npm ERR! 
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Darwin 12.2.0
npm ERR! command "node" "/usr/local/bin/npm" "search" "bower"
npm ERR! cwd /Users/chietala
npm ERR! node -v v0.10.4
npm ERR! npm -v 1.2.18
npm ERR! path /Users/chietala/.npm/-/all/.cache.json
npm ERR! code EACCES
npm ERR! errno 3
npm ERR! stack Error: EACCES, open '/Users/chietala/.npm/-/all/.cache.json'
npm ERR! 
npm ERR! Additional logging details can be found in:
npm ERR!     /Users/chietala/npm-debug.log
npm ERR! not ok code 0

当前回答

John Papa指出了这个问题背后的历史和原因,并给出了一个可靠的解决方案:

John Papa的步骤是:

使用brew安装没有npm的节点更新.bash_profile/.bashrc,让npm和node知道安装和查找包的位置使用brew更新节点,使用npm更新自身

希望这能帮助好奇的人!

其他回答

事实上,我也有同样的问题。我在运行Ubuntu。我的问题出现了,因为我丢失了Ubuntu的公钥。甚至没有更新我的系统。它给出了GPG错误。在这种情况下,您可以使用以下命令重新获取密钥:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys <key in GPG error>

之后,npm工作正常!

小心!!!小心!!!小心!!!

chown或chmod不是解决方案,因为存在安全风险。

相反,请执行以下操作:

首先检查npm指向的位置,如果您调用:

npm config get prefix

如果返回/usr,则可以执行以下操作:

mkdir ~/.npm-global
export NPM_CONFIG_PREFIX=~/.npm-global
export PATH=$PATH:~/.npm-global/bin

这将在主目录中创建一个npm目录,并将npm指向它。

要使这些更改永久化,必须将export命令添加到.bashrc中:

echo -e "export NPM_CONFIG_PREFIX=~/.npm-global\nexport PATH=\$PATH:~/.npm-global/bin" >> ~/.bashrc

没有人提到这一点,但实际上不需要弄乱权限或单独的npm安装,只需为命令指定不同的缓存文件夹即可解决问题

npm install --cache .npm
npm run build --cache .npm

这将创建一个本地.npm文件夹

其他答案是建议将系统目录的所有权或权限更改为特定用户。我强烈反对这样做,这可能会变得非常尴尬,可能会搞乱整个系统!

这里有一种更通用、更安全的方法,也支持多用户。

为节点用户创建新组,并将所需用户添加到此组。然后将依赖于节点的文件/目录的所有权设置为此组。

# Create new group
sudo groupadd nodegrp 

# Add user to group (logname is a variable and gets replaced by the currently logged in user)
sudo usermod -a -G nodegrp `logname`

# Instant access to group without re-login
newgrp nodegrp

# Check group - nodegrp should be listed as well now
groups

# Change group of node_modules, node, npm to new group 
sudo chgrp -R nodegrp /usr/lib/node_modules/
sudo chgrp nodegrp /usr/bin/node
sudo chgrp nodegrp /usr/bin/npm

# (You may want to change a couple of more files (like grunt etc) in your /usr/bin/ directory.)

现在,您可以以用户身份轻松安装模块

npm install -g generator-angular

某些模块(咕噜、弓箭手、溜溜球等)仍需要作为根安装。这是因为它们在/user/bin/中创建符号链接。

Edit

3年后,我建议使用节点版本管理器。它为你节省了很多时间和麻烦。

最好的解决方案是由npm文档提供的。


对于Ubuntu,建议的解决方案是选项#2

简要步骤:为全局安装创建目录:mkdir~/.npm全局

配置npm以使用新目录路径:npm配置集前缀“~/.npm全局”npm-config-get-prefix可以帮助您验证前缀是否已更新。结果将是<Your Home Directory>/.npm global

打开或创建~/.profile文件并添加此行:导出PATH=~/.npm全局/bin:$PATH

返回命令行,更新系统变量:源~/.profile

您也可以使用相应的ENV变量代替步骤2-4(例如,如果您不想修改~/.profile):

NPM_CONFIG_PREFIX=~/.NPM全局


对于Mac,建议的解决方案是选项#3

在Mac OS上,您可以使用Homebrew包管理器完全避免此问题

brew安装节点