Fixing npm for Homebrew Users

I have installed node via brew and when I tried to upgrade node version via brew upgrade, I found that npm version was not upgraded correctly. After running brew upgrade, my node version is 12.1.0 but my npm version is still 6.4 instead 6.9.

Here is how I fixed the problem.

  1. Backup existing npm global package folder /usr/local/lib/node_modules
    # Bonus point to export a parsable list for later installation
    $ npm list --global --parseable --depth=0 | sed '1d' | awk '{gsub(/\/usr\/local\/lib\/node_modules\//,"",$1); print}' > export-npm-file
    # Replace \/usr\/local\/lib\/node_modules\/ part to be the actual location of global packages. Make sure you have /xxxx/
    # surrounds the actual path because that's the syntax of regular expression
  2. Delete /usr/local/lib/node_modules
  3. brew uninstall node
  4. brew install node
  5. Reinstall global packages using npm install -g xxx
    # If you exported packages in step 1, then do
    $ xargs npm install --g < export-npm-file