我可以使用sudo安装NPM包吗?

Can I Install NPM Packages Using Sudo?

最近提示我使用 npm install -g npm 安装 NPM 补丁,但此过程失败了。以下是错误消息的摘录。

npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/npm
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/npm/node_modules

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.

使用 sudo 安装补丁是否安全?如果不是,此问题的正确解决方法是什么?

是的,你可以这样做,但是不,这不安全。很多人这样做,但他们不应该这样做。如果你使用 sudo 安装,那么所有包的依赖项和子依赖项(可以是非常多的包)都可以 运行 生命周期脚本作为 root,基本上可以做任何他们想做的事。您可以使用 --ignore-scripts 缓解这种情况,但您安装的东西可能无法正常工作。

更好的解决方案在 the npm docs about this topic: Install node and npm with a version manager (like nvm) 或配置 npm 以在不需要使用 sudo.

的目录中进行全局安装

综上所述,对于您的具体情况——仅更新 npm 本身——使用 sudo 是一种非常常见的解决方案,尽管它并不是那么可取。如果您使用的是开发机器(例如您的个人笔记本电脑),则使用版本管理器安装 npm 是更好的主意。