关于使用 npm -g 在 Linux 服务器上遇到的权限问题

Linux1年前 (2022)发布 yekei
63 0

注:阅读本文需要包含以下前缀知识:

  • 了解 JavaScript
  • 了解 Node.js
  • 了解 Linux 的用户与权限、Linux 常用命令

#0 详细的错误日志

ubuntu@VM-0-8-ubuntu:~$ npm install -g pm2@latest



npm ERR! code EACCES



npm ERR! syscall mkdir



npm ERR! path /usr/local/lib/nodejs/node-v16.13.1-linux-x64/lib/node_modules/pm2



npm ERR! errno -13



npm ERR! Error: EACCES: permission denied, mkdir '/usr/local/lib/nodejs/node-v16.13.1-linux-x64/lib/node_modules/pm2'



npm ERR! [Error: EACCES: permission denied, mkdir '/usr/local/lib/nodejs/node-v16.13.1-linux-x64/lib/node_modules/pm2'] {



npm ERR!   errno: -13,



npm ERR!   code: 'EACCES',



npm ERR!   syscall: 'mkdir',



npm ERR!   path: '/usr/local/lib/nodejs/node-v16.13.1-linux-x64/lib/node_modules/pm2'



npm ERR! }



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.







npm ERR! A complete log of this run can be found in:



npm ERR!     /home/ubuntu/.npm/_logs/2022-02-16T05_19_47_471Z-debug.log

#1 问题分析

不难看出,上面提示的主要错误来源为权限不足。关键词:permission denied。在尝试使用 sudo npm install -g pm2@latest 无果后(因为 sudo 状态下不支持这个命令,此亦为一条解决之道:将 npm 添加到”可sudo”的列表里【未尝试】),了解到此问题可以通过用包管理器重新安装 node 来解决。

#2 解决办法

参考:Resolving EACCES permissions errors when installing packages globally | npm Docs

对上述参考的简要解读:

上述参考主要提出了2种解决方案:

  1. 选择一款包管理器来重新安装一个 npm
  2. 手动修改目前 npm 可执行程序的默认路径

本文主要记录采用第一种方法解决。

#3 实施解决方案

包管理器参考:通过包管理器安装 Node.js

本文选择了 fnm 这个包管理器:

Img

3.1 安装

重要:首先卸载掉系统的 nodejs,使用 apt 或手动删除文件均可,确保 node 命令被释放出来

curl -fsSL https://fnm.vercel.app/install | bash

可能需要手动刷新一下 .bashrc 文件,或者退出当前用户重新登录一下。具体看上述命令执行完的提示信息。

3.2 使用 fnm

fnm 的使用命令参考其对应的 Github 页:GitHub – Schniz/fnm: 🚀 Fast and simple Node.js version manager, built in Rust

首先,安装 node.js 的某一个版本:本文选择 16.13.1

fnm install 16.13.1



fnm use 16.13.1

查看当前使用的node版本:

fnm current

如果显示为 none,则是因为没有use上,重新来 use 一遍即可。use 上后,在终端输入 node(注意如果没有 use 上的话,输入node会提示命令不存在)即可开始使用 node。

3.3 验证是否解决问题

此时,采用 npm install -g pm2@latest 即可成功全局安装(因为此时的node,包括npm都是安装在用户自己的Home目录下,可通过 which node 查看,结果形如:/run/user/500/fnm_multishells/18602_1645004672968/bin/node 代表成功应用)。可以愉快的使用后端,再也不用担心掉线啦。

© 版权声明

相关文章

暂无评论

暂无评论...