Kirsle.net logo Kirsle.net

Sudo-less NPM Global Installs

March 18, 2016 by Noah

If you're a JavaScript developer (in the Node.js world), you're probably used to typing in commands like sudo npm install -g gulp-cli (unless you installed Node via Homebrew on Mac OS X so that your local user account owns /usr/local). But I never liked the idea of having files installed under /usr/local (root-owned or otherwise) that my package manager didn't know about, and would prefer to have these global npm commands installed into a user-specific root instead.

Here's how to set this up.

First, edit your .bashrc (or .bash_profile or .zshrc) to add some environment variables:

# Node/npm
export NPM_PACKAGES="${HOME}/.npm-global-pkg"
export NODE_PATH="${NPM_PACKAGES}/lib/node_modules:${NODE_PATH}"
export PATH="${NPM_PACKAGES}/bin:$PATH"

What this does:

  • $NPM_PACKAGES is a variable we use so we don't have to define the path more than once (Node/npm doesn't use this variable itself). We want our global modules to be installed under ~/.npm-global-pkg
  • $NODE_PATH is used by Node when you require() a module; if the module isn't in the local project's directory it will try to import it from our new global directory.
  • We update our $PATH to add ~/.npm-global-pkg/bin, so when we install a global npm package that contains a command line program (like gulp, coffee, bower, etc.) it's available as a command in our shell.

Then, create or edit the file ~/.npmrc to specify the same path from $NPM_PACKAGES as your npm prefix:

prefix = ${HOME}/.npm-global-pkg

This tells Node where to install packages when you run npm install -g.

Restart your terminal session or re-source your configuration so the environment variables take effect. Now, when you run a command like (the sudo-less!) npm install -g coffee-script, it will place its binary in ~/.npm-global-pkg/bin/coffee.

Tags:

Comments

There are 0 comments on this page. Add yours.

Add a Comment

Used for your Gravatar and optional thread subscription. Privacy policy.
You may format your message using GitHub Flavored Markdown syntax.