Skip to content

Instantly share code, notes, and snippets.

@gudleik
Last active April 28, 2023 21:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save gudleik/7ae3ef00f42440671f16 to your computer and use it in GitHub Desktop.
Save gudleik/7ae3ef00f42440671f16 to your computer and use it in GitHub Desktop.
Node.js direnv setup
# Either use node version specified in package.json
use node package.json
# Or a specific version
use node 5.0.0
# Rest of direnv setup..
export FOO=BAR
use_node() {
layout node
local node_version=$1
if [ "$node_version" == "package.json" ]; then
# Requires jq: `brew install jq`
node_version=`jq --raw-output .engines.node package.json | tr -d "<=> "`
fi
local node_path=${NODE_DIR:-/usr/local/n/versions/node}
if [ -x "$node_path/$node_version/bin/node" ]; then
PATH_add $node_path/$node_version/bin
elif [ -x "$node_path/v$node_version/bin/node" ]; then
# Support nvm users (nvm prefixes versions with 'v')
PATH_add $node_path/v$node_version/bin
else
echo "!!! Node.js version $node_version is not installed"
fi
export NODE_PATH=./node_modules
}
@gudleik
Copy link
Author

gudleik commented Nov 3, 2015

The script assumes node versions are installed using n in /usr/local/n/versions/node, but can be changed using the NODE_DIR env variable.

Installation instructions:

  • brew install direnv
  • brew install jq (for parsing package.json)
  • Copy contents of direnvrc to ~/.direnvrc or ~/.config/direnv/direnvrc

To use a specific version in your project, put this in your project's .envrc

use node 5.2.0

To specify a global node version, put this in ~/.envrc

use node 5.2.0

If you want to use the node version as specified in package.json, make sure package.json contains the "engines" keyword:

"engines": {
  "node": "5.0.0"
}

Then put this in .envrc:

use node package.json

@rstackhouse
Copy link

@gudleik, this is quite old. Was wondering if you still do it this way or if you use nvm now. TIA.

@gudleik
Copy link
Author

gudleik commented Feb 17, 2023

heh I had forgotten about this. Don't use this or nvm anymore, just lts node installed with homebrew

@rstackhouse
Copy link

Time goes by. We find better ways. If you aren't using nvm, what are you using?

@gudleik
Copy link
Author

gudleik commented Feb 19, 2023

I don't switch between node versions anymore, so I just use the latest LTS version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment