Installing node through Homebrew can cause problems with npm for globally installed packages. To fix it quickly, use the solution below. An explanation is also included at the end of this document.
This solution fixes the error caused by trying to run npm update npm -g
. Once you're finished, you also won't need to use sudo
to install npm modules globally.
Before you start, make a note of any globally installed npm packages. These instructions will have you remove all of those packages. After you're finished you'll need to re-install them.
Run the following commands to remove all existing global npm modules, uninstall node & npm, re-install node with the correct defaults, configure the location for global npm modules to be installed, and then install npm as its own pacakge.
export NPM_VERSION=6.1.0
rm -rf /usr/local/lib/node_modules
brew uninstall node
brew install node --without-npm
echo prefix=~/.npm-packages >> ~/.npmrc
curl -O https://registry.npmjs.org/npm/-/npm-${NPM_VERSION}.tgz
tar xzf npm-${NPM_VERSION}.tgz
cd package
node bin/npm-cli.js install -gf --prefix=~/.npm-packages ../npm-${NPM_VERSION}.tgz
cd ..
rm -rf package npm-${NPM_VERSION}.tgz
Node and npm should be correctly installed at this point. The final step is to add ~/.npm-packages/bin
to your PATH
so npm and global npm packages are usable. To do this, add the following line to your ~/.bash_profile
:
export PATH="$HOME/.npm-packages/bin:$PATH"
Now you can re-install any global npm packages you need without any problems.