NPM全局安装软件包时解决EACCES权限错误

NPM全局安装软件包时解决EACCES权限错误

Resolving EACCES permissions errors when installing packages globally

npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

如果在尝试全局安装软件包时看到EACCES错误,则可以:

  • 使用节点版本管理器重新安装npm(推荐)
  • 手动更改npm的默认目录

使用Node.js包管理器,重新安装NPM

这是避免权限问题的最佳方法。 要使用节点版本管理器重新安装npm,请按照“下载并安装Node.js和npm”中的步骤进行操作。 在安装节点版本管理器之前,不需要删除当前版本的npm或Node.js。

要下载最新版本的npm,请在命令行上运行以下命令:

[sudo] npm install npm -g

手动更改npm的默认目录

注意:本部分不适用于Microsoft Windows。

为了最大程度地减少权限错误的可能性,您可以将npm配置为使用其他目录。 在此示例中,您将在主目录中创建并使用隐藏目录。

1、 备份电脑。

2、在命令行的主目录中,为全局安装创建目录:

 mkdir ~/.npm-global

3、 配置npm以使用新的目录路径:

npm config set prefix '~/.npm-global'

4、在您喜欢的文本编辑器中,打开或创建〜/ .profile文件并添加以下行:

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

5、在命令行上,更新系统变量:

source ~/.profile

6、要测试新配置,请在不使用sudo的情况下全局安装软件包:

npm install -g jshint

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

NPM_CONFIG_PREFIX=~/.npm-global

npx:运行全局命令的替代方法

如果您使用的是npm 5.2或更高版本,则可能要考虑将npx作为运行全局命令的替代方法,尤其是在您仅偶尔需要命令的情况下。

posted @ 2019-09-23 15:24  大圣巴巴  阅读(9168)  评论(0编辑  收藏  举报