Skip to content

Instantly share code, notes, and snippets.

@usefulthink
Last active August 17, 2017 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save usefulthink/a7df81859a924a33516d2c7e55632fca to your computer and use it in GitHub Desktop.
Save usefulthink/a7df81859a924a33516d2c7e55632fca to your computer and use it in GitHub Desktop.
automatically add current node-binary path to $PATH
LAST_PWD=""
LAST_NPM_BIN=""
# find the npm binary path for a given directory ($1).
# Mostly equivalent to calling `npm bin` (except it doesn't report
# non-existing directories), but around 40x faster.
function fastNpmBin() {
local dir="${1}"
local candidate=""
while [ "${dir}" != "/" ] ; do
candidate="${dir}/node_modules/.bin"
if [ -d "${candidate}" ] ; then
echo -n "${candidate}"
return 0
fi
dir=`dirname "${dir}"`
done
return 1
}
function updatePath() {
# dont do anything if we did stay in the same directory
if [ "$(pwd)" == "${LAST_PWD}" ] ; then return; fi
# store pwd to prevent rechecking
LAST_PWD="$(pwd)"
# get npm bin
local npmBin="$(fastNpmBin ${LAST_PWD})"
# check if npmBin changed since the last path-update
if [ "${npmBin}" != "${LAST_NPM_BIN}" ] ; then
# purge all entries for commands from node_modules/.bin from the
# path-lookup cache
hash -l | grep node_modules/.bin | while read x x x x name ; do
hash -d "${name}"
done
LAST_NPM_BIN="${npmBin}"
# remove any previous PATH-entries containing `node_modules/.bin` and
# prepend the new bin-dir
PATH="${npmBin}$(
IFS=':'
for d in $PATH ; do
[[ "${d/node_modules\/.bin/}" != "${d}" ]] || printf ":$d"
done
)"
# remove a trailing colon (if $npmBin is empty)
export PATH=${PATH#:}
fi
}
export PROMPT_COMMAND=updatePath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment