Skip to content

Instantly share code, notes, and snippets.

@aa6my
Forked from simov/README.md
Created January 16, 2020 03:37
Show Gist options
  • Save aa6my/399cb9c6d10d43400c317e98df0f6868 to your computer and use it in GitHub Desktop.
Save aa6my/399cb9c6d10d43400c317e98df0f6868 to your computer and use it in GitHub Desktop.
Run `node` scripts using `nvm` and `crontab` without hardcoding the node version

Run node scripts using nvm and crontab without hardcoding the node version

cronjob.env.sh

#!/bin/bash

# NVM needs the ability to modify your current shell session's env vars,
# which is why it's a sourced function

# found in the current user's .bashrc - update [user] below with your user! 
export NVM_DIR="/home/[user]/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"  # This loads nvm

# uncomment the line below if you need a specific version of node
# other than the one specified as `default` alias in NVM (optional)
# nvm use 4 1> /dev/null

crontab -e

# paths can be relative to the current user that owns the crontab configuration

# NVM should be sourced here!
# otherwise `$(which node)` in `script.sh` won't work!
*/1 * * * *     (. ~/path/cronjob.env.sh; ~/path/script.sh >> ~/path/file.log; )

# alternatively the node version can be specified here
*/1 * * * *     (. ~/path/cronjob.env.sh; nvm use 4 1> /dev/null; ~/path/script.sh >> ~/path/file.log; )

script.sh

#!/bin/bash

# paths can be relative to the current user that owns the crontab configuration

# $(which node) returns the path to the current node version
# either the one specified as `default` alias in NVM or a specific version set above
# executing `nvm use 4 1> /dev/null` here won't work!
$(which node) ~/path/script.js

script.js

console.log(process.version)
#!/bin/bash
# NVM needs the ability to modify your current shell session's env vars,
# which is why it's a sourced function
# found in the current user's .bashrc - update [user] below with your user!
export NVM_DIR="/home/[user]/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
# uncomment the line below if you need a specific version of node
# other than the one specified as `default` alias in NVM (optional)
# nvm use 4 1> /dev/null
console.log(process.version)
#!/bin/bash
# paths can be relative to the current user that owns the crontab configuration
# $(which node) returns the path to the current node version
# either the one specified as `default` alias in NVM or a specific version set above
# executing `nvm use 4 1> /dev/null` here won't work!
$(which node) ~/path/script.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment