How to run a node script on a schedule using cron
- scheduling a Node.js script as a cron job won’t work by default on a Mac because cron’s default SHELL and PATH environment variables are different from the ones in your terminal and don’t include your zshrc settings and local commands like node, nvm or npm.
- Here’s how to change that so your scripts will run the same way in cron as they do when you run them manually in your terminal:
- match a way that uses a SHELL and PATH that don’t including node, npm, nvm/fnm (so Node version doesn’t have to be hardcoded)
-
- Update PATH in crontab to point to your local commands
-
- Save your script as an executable .sh file
-
- Set zsh as env in script (since cron uses SHELL=‘bin/sh’ by default)
-
- Source .zshrc in script
-
- Schedule job to run as often as you want
-
- Pipe all output to a file so you can inspect what happened (console.logs, errors, etc)
-
- Give cron full disk access (if your script reads/write from/to the file system) — System Preferences > …
Links:
- how to set the PATH variable in crontab so the commands that work in your terminal (including nvm/fnm, node, npm) will also work in a cron job: https://askubuntu.com/questions/23009/why-crontab-scripts-are-not-working
- ⭐️ how to set path variable in crontab: https://stackoverflow.com/a/57438635/8802485
- how to source zshrc in your script: https://unix.stackexchange.com/questions/67940/cron-ignores-variables-defined-in-bashrc-and-bash-profile
- how to schedule cron jobs — crontab.guru
Sending emails
- Sending Email Using SendGrid
- Resend • Build, test, and send transactional emails at scale 🛠️
Inbox
- Test ES Modules with Node.js 18 Test Runner - Includes how to use it with TS files - TypeScript TV with Benny
- Test runner - Jest/Vitest alternative - Node docs