Per-user package installation with NPM on Linux

I find the node.js package manager, npm, to be a little annoying. It offers two options for installing software:

  • Install to the current directory (for example, to use with a current project)
  • Install system-wide

The second is obviously a problem if one doesn’t have root priviliges, and the first is incredibly annoying for installing software, as there isn’t an easy way to add the resulting installed binary to your $PATH.

I much prefer the behaviour of cabal-install, the Haskell package manager, which installs locally to $HOME/.cabal/ on a per-user basis.

To get Node.js to mimic this behaviour is quite simple. In your ~/.zshrc or ~/.bashrc simply add the line

alias npm="PREFIX=$HOME/.npm-modules/ npm"

This sets the path npm uses to install modules to a local directory: npm-modules. You can now set your $PATH to include binaries installed via npm by including the directory $HOME/.npm-modules/bin/.