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作為運行全局命令的替代方法,尤其是在您僅偶爾需要命令的情況下。