Dynamically Changing $PATH for different Node projects

When I started working with Node, I did a lot of the work locally. I was working on several local projects and was having trouble keeping my $PATH up to date. I’ve recently found a solution that dynamically sets your $PATH to include node_packages/.bin in whatever directory you’re working.

Add the following to the bottom of your .bashrc or .bash_profile.

# Save old PATH 
_PATH=$PATH 

# Function to update PATH to include `npm bin` output 
function nodePath() { 
    export PATH=$(npm bin):$_PATH 
} 

# Set nodePath to be run on prompt 
PROMPT_COMMAND=nodePath

This takes advantage of the PROMPT_COMMAND environment variable, which runs an assigned function before your BASH terminal displays a prompt. Large functions may slow down the shell, but I haven’t noticed a performance issue at all using it.