When encountering EACCES errors, it is typically due to npm lacking sufficient permissions when attempting to install packages globally. This issue commonly occurs on Unix-like systems (such as Linux and macOS), particularly when attempting to use the default global installation location (e.g., /usr/local). Several methods can resolve this issue:
1. Change npm's Default Directory
A recommended approach is to change npm's default directory to a location that does not require sudo permissions. This avoids the need for sudo permissions during each global package installation.
Steps:
-
Create a new directory in your home directory for global installations:
bashmkdir ~/.npm-global -
Configure npm to use the new directory path:
bashnpm config set prefix '~/.npm-global' -
In your shell configuration file (e.g.,
.bashrcor.zshrc), add or modify the PATH environment variable to include the new global installation path:bashexport PATH=~/.npm-global/bin:$PATH -
Update your system environment variables:
bashsource ~/.bashrc # or the corresponding configuration file -
Now you can install npm packages globally without using sudo.
2. Add sudo When Using npm or npx
If you only occasionally need to install global npm packages, you can add sudo before the command to provide the necessary permissions.
For example:
bashsudo npm install -g <package-name>
Note: Frequent use of sudo for global installations may cause security issues and other system-level conflicts.
3. Change Permissions of the Global Installation Directory
Another less recommended method is to change the permissions of the node_modules directory to allow the current user access. This can be achieved by modifying the folder owner or permissions.
For example:
bashsudo chown -R $(whoami) /usr/local/lib/node_modules sudo chown -R $(whoami) /usr/local/bin sudo chown -R $(whoami) /usr/local/share
Note: This method may pose security risks as it relaxes access control to critical system directories.
Conclusion
Typically, changing npm's default installation directory is the safest and most durable solution for resolving EACCES issues. This not only avoids permission problems but also maintains system security and stability. When installing npm packages globally, avoid using sudo unless absolutely necessary.