安装Node.js、npm及Serverless时遇权限错误求助
Hey there! I totally get how frustrating permission errors can be when you're just starting out with Node.js and npm. Let's walk through a few solutions to get Serverless installed smoothly—no more EACCES errors!
First, let's break down the problem: The error message says you don't have write access to /usr/lib/node_modules, which makes sense because by default, this system directory is owned by the root user. When you run npm install -g without elevated permissions, your regular user account can't write to it.
Here are three ways to fix this, ordered from quick-and-dirty to the most recommended long-term solution:
1. Quick Fix: Use Sudo to Install (Not Ideal for Regular Use)
If you just need Serverless installed right now, you can run the install command with sudo to temporarily get root privileges:
sudo npm install -g serverless
⚠️ Note: While this works immediately, using sudo for every global npm install can lead to permission conflicts down the line (like your user not being able to modify packages later). Use this sparingly.
2. Change Permissions on System Directories
You can transfer ownership of the npm-related system directories to your user account, so you don't need sudo anymore:
First, confirm your npm prefix (default is /usr):
npm config get prefix
Then run these commands to change ownership:
sudo chown -R $USER:$USER /usr/lib/node_modules sudo chown -R $USER:$USER /usr/bin sudo chown -R $USER:$USER /usr/share
After this, you can run npm install -g serverless normally. Just keep in mind that if other users share this Ubuntu system, changing system directory permissions might cause issues for them.
3. Best Practice: Use a User-Specific Global Directory (Recommended)
This is the cleanest solution—we'll configure npm to install all global packages in a directory inside your user folder, so you never have to deal with system permissions again.
Follow these steps:
- Create a dedicated directory for your global npm packages:
mkdir -p ~/.npm-global
- Tell npm to use this new directory as the global prefix:
npm config set prefix '~/.npm-global'
- Update your shell's PATH so it can find the globally installed tools. Open your shell config file (for Bash, it's
~/.bashrc; for Zsh, it's~/.zshrc):
nano ~/.bashrc
Add this line at the end of the file:
export PATH=~/.npm-global/bin:$PATH
Save and exit the editor (press Ctrl+O, hit Enter, then Ctrl+X).
4. Make the PATH change take effect immediately:
source ~/.bashrc
- Now install Serverless without any permission issues:
npm install -g serverless
Verify the Installation
Once the install finishes, check if Serverless is working:
serverless --version
If you see a version number pop up, you're all set!
内容的提问来源于stack exchange,提问作者some_programmer

