Execute nodejs project via cron using nvm

In my latest tiny project, I explored Playwright — a browser automation tool which focuses on E2E testing. Just for the sake of exploring, I use it not as an E2E testing tool but rather a scheduled website monitoring. Basically I wanted to know whether the content I’m looking for is available or not. If it is, I’m sending myself a notification through Telegram.

Everything was set up: the script will run when I do npx playwright test and will notify me as soon as the test failed. So I naturally choose the greatest tool of all time to schedule the run: cron. I had been using it dozens of times for dozens of things, so this one should be trivial right? Wrong.

The cron was executed, but somehow I don’t get notified. After checking the logs, the error message was node: command not found — it seems that node isn’t recognized. Weird.

Turned out, since I’m using nvm to manage multiple node versions in my machine, the setup is a bit different. Basically cron doesn’t know nvm exists, hence it doesn’t know that node and npm exist so it just decided to fail.

I googled a bit and stumbled upon this article that mentioned the same problem, but the script there doesn’t work in my case. Here’s what works:

# File schedule.sh

# Load nvm first to enable node, npm, npx, etc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

# Run the test
npx playwright test

And by putting */30 * * * * sh schedule.sh in the crontab file, the script works flawlessly.