Running a Node.js Script with Cron
Use the full path to node because cron has a minimal PATH. Change into the project directory first so relative requires and .env files resolve. Log output to catch crashes.
The crontab line
0 * * * * cd /opt/app && /usr/bin/node script.js >> /var/log/node-job.log 2>&1
Find your node path with which node — with nvm it is often /home/user/.nvm/versions/node/vXX/bin/node, not /usr/bin/node.
nvm-installed Node
nvm sets PATH in ~/.bashrc, which cron ignores. Either use the absolute versioned path above, or source nvm in the job:
0 * * * * . ~/.nvm/nvm.sh && cd /opt/app && node script.js >> /var/log/node-job.log 2>&1
Environment variables
Load your .env before node if the script needs it: prefix with . /opt/app/.env; or use a package like dotenv inside the script.
FAQ
What cron line runs a Node.js script?
0 * * * * cd /opt/app && /usr/bin/node script.js >> /var/log/node-job.log 2>&1. Use the absolute node path and cd into the project first.
Why does node work in the shell but not in cron?
cron uses a minimal PATH and ignores ~/.bashrc where nvm sets things up. Use the full versioned node path or source nvm inside the job.
How do I find my node path for cron?
Run which node in your terminal and paste that absolute path into the crontab entry.