I know that you can run a Node.js script in Crontab by doing something like:
0 * * * * node /path/to/your/script.js
But I want to run a Node.js app, not a script, using Crontab. I created a Node.js app in order to write some automated tests using Mocha, Chai and Selenium, and I want to run it periodically by using Crontab. How would I go about doing this? I currently run my app by writing in the command line:
npm run api-pro
Where api-pro is a script from my package.json that invokes some tests for the production api.
Note that if I simply try to write a Crontab job with the command "npm run api-pro" it doesn't recognize the command npm (and obviously I do have Node installed in my computer).
My guess is that the user cron use do not configure the PATH in the same way as your user, and do not know node nor npm.
What you can try is to use the command which node to know where your node binary is (/some/path/to/node)
Then you can use the absolute path in your crontab:
0 * * * * /some/path/to/node /path/to/your/script.js
EDIT:
The difference between adding node and npm to $PATH and using absolute paths is that absolute path will work for one executable, since Linux will not have to search the PATH.
Adding to the PATH will make Linux recognize node and npm just as in your user. The fact that they are in the same folder do not affect that.
For anyone trying to run with npm, here were my steps to get it working on MacOS 12.3.1, using node/npm installed by brew.
Note, this is inflexible, and the PATH will need to be updated if brew updates its paths again:
echo $PATH
// /opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:...
which npm
// /opt/homebrew/bin/npm
EDITOR="vim" crontab -ePATH={what you copied from step 1}
* * * * * cd {your_project_dir_where_package.json_lives} && {location_of_npm_from_step_1} run start >>/tmp/crontab.log 2>&1
Note: The >>/tmp/crontab.log 2>&1 is to help you debug. You can tail -f /tmp/crontab.log in another terminal to watch for STDOUT or STDERR
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With