Skip to content

Instantly share code, notes, and snippets.

@petitchevalroux
Last active November 13, 2017 10:20
Show Gist options
  • Save petitchevalroux/37077059f781b502ca9081f43bcd5ff0 to your computer and use it in GitHub Desktop.
Save petitchevalroux/37077059f781b502ca9081f43bcd5ff0 to your computer and use it in GitHub Desktop.
Adding locally installed node.js binaries to $PATH
#!/bin/bash
# To add locally installed node.js binaries to $PATH
# Add the following code to your ~/.profile|~/.bash_profile|...
# If npm is available
if hash npm 2>/dev/null; then
# previously appended string
_NMB_PREVIOUS=""
_PREVIOUS_PATH=""
function addNodeModulesBinariesToPath() {
CURRENT_PATH=$(pwd);
# Avoid npm bin when path does not change
if [ "${CURRENT_PATH}" != "${_PREVIOUS_PATH}" ]; then
NMB_PATH=$(npm bin)
# Avoid updating path when node_modules binaries does not change
if [ "${NMB_PATH}" != "${_NMB_PREVIOUS}" ]; then
# Remove previously added string if non empty
if [ -n "${_NMB_PREVIOUS}" ]; then
PATH=$(echo $PATH | sed -e "s|${_NMB_PREVIOUS}||")
fi
# Append current binary path to path
export PATH="$PATH:${NMB_PATH}"
export _NMB_PREVIOUS=":${NMB_PATH}"
fi
fi
_PREVIOUS_PATH=${CURRENT_PATH}
}
# Run addNodeModulesBinariesToPath after each command
export PROMPT_COMMAND="${PROMPT_COMMAND};addNodeModulesBinariesToPath"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment