Change NPM Global Directory

On many Linux distros NPM works fine except that it will throw permission errors when trying to install global packages (Eg. npm i -g nodemon). While you might be tempted...

a year ago

Latest Post Automatic Offline Backup With a Raspberry Pi by Tyler Moon

On many Linux distros NPM works fine except that it will throw permission errors when trying to install global packages (Eg. npm i -g nodemon). While you might be tempted to just brute force the permissions by using sudo npm i -g nodemon or sudo chmod -R /usr/local/node_modules there is an easier and safer way to fix this issue. You can just change where NPM installs its global packages to a location where your user has permissions.

Note: If you have multiple users on a system and want to share NPM packages between them this method will not work as it will be in a user specific directory. You can however setup a directory where all users have permission and follow the same directions but substitute for that directory

Prerequisites

New Directory

Start up your terminal emulator of choice and run the following command to create a new directory for global installations under your home directory

mkdir ~/.npm-global

Next configure NPM to use the new directory instead of its default

npm config set prefix '~/.npm-global'

With your preferred text editor open ~/.profile and add the new NPM directory to your path. This allows you to execute the global NPM commands without specifying the directory.

export PATH=~/.npm-global/bin:$PATH

Now either restart your terminal or run the following command to reload the system variables

source ~/.profile

Summary

And now you should be able to install global NPM packages with a -g flag on the install command. All the global NPM packages should be downloaded to ~/.npm-global and execute out of the  ~/.npm-global/bin directory.

Tyler Moon

Published a year ago

Comments?

Leave us your opinion.