npm Without Sudo

Published | Go Back

Recently, I have to re­in­stall npm. It’s a good time to jot down how to in­stall npm lo­cally so that no sudo is re­quired when us­ing npm.

The whole story be­gins with this is­sue. Basically, on my ma­chine, npm 5.5.1 crashes every time when I try to up­date or in­stall pack­ages for Node.js 9.2.0. The so­lu­tion is to unin­stall npm and re­in­stall it with a higher ver­sion like 5.6.0.

It’s de­bat­able whether npm should be in­stalled lo­cally in the user home di­rec­tory or at the sys­tem level. Personally, I pre­fer not us­ing sudo for npm.

Here is the main ref­er­ence on how to do this. For me, I did the fol­low­ing steps:

  1. Add prefix=~/.npm-packages to ~/.npmrc.
  2. Add the fol­low­ing lines to ~/.xprofile:
    # Tell npm about the packages:
    export NPM_PACKAGES="$HOME/.npm-packages"
    # Tell Node.js about the packages:
    export NODE_PATH="$NPM_PACKAGES/lib/node_modules"
    export PATH="$NPM_PACKAGES/bin:$PATH"
    export MANPATH="$NPM_PACKAGES/share/man:$MANPATH"
  3. Reboot so that the new en­vi­ron­ment vari­ables take ef­fect.
  4. Download the npm mod­ule from here.
  5. Install npm us­ing the nor­mal way: ./configure, make, and make install.

Note that the en­vi­ron­ment vari­able set­tings and where to put them are spe­cific to my ma­chine. You might have to change them to fit in your sys­tem.