There's a bit of a headache going around in respect to global npm permissions. For those of us working on Unix-based systems, it's not uncommon to come across error messages complaining about your user permissions whenever installing new npm packages, especially when installing them globally.
If errors like the one below look familiar, you're not alone:
This is a textbook case of being trigger-happy with the sudo command. If you're installing npm as a user other than root, it's a badidea to install Node + npm with the sudo command. If a non-root user installs these dependencies by escalating privileges via sudo, the installation will succeed indeed. However, we've just created a scenario where the user in question does not have permission to modify global npm the user just installed (nor modify/install packages). When we installed Node/npm with sudo, we handed exclusive ownership to the root user. That would mean we'd have to specify sudo before every global package install, which is annoying, but more importantly unrealistic.
It gets worse. Npm packages which require post-install scripts to be run simply become impossible to install. Sometimes you might be able to get away with the following, but only if the scripts aren't necessary:
When the scripts are necessary, like in the case of node-sass, we're shit outta luck. Using the --ignore-scripts flag just results in a broken install. Attempting to install using sudo looks like this:
Why does this happen? Because by default, the post-install scripts attempt to run as the current user. Since the current user doesn't have permissions to mess with packages installed globally, the installation ultimately fails. To fix this, we need to reinstall Node the correct way.
I'm working under the assumption that we're using Ubuntu or a Debian-based Linux distro. The first thing we need to do is remove Node:
Verify that Node is gone:
If a folder path is returned by the above, nuke it. That should leave us ready for a fresh install.
Since we're on a Debian system, we need to install Node via Nodesource. I'd recommend running this in the /tmp folder, or wherever you like to dump things saved from the internet:
Now would be a good time to get the latest npm as well:
When the installation is complete, check to see if everything worked:
Create a New Global NPM Directory
With Node reinstalled, we can move on to creating and configuring a new directory to hold our global npm modules. You can name this what you want, but it's generally recommended to name this npm-global or something of the sort. Don't use sudo!
Now we can configure npm to recognize this folder:
Next, we need to add this to our PATH. This should go in ~/.bashrcor ~/.bash_profile, depending on which you use:
You Did Good
That should do it! From now on, remember to stray away from using sudo when installing Node, npm, or even modifying npm packages. The npm documentation explicitly recommends against this, but it's all good. We all make mistakes.