'Not able to use Node.js and Crontab
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).
Solution 1:[1]
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.
Solution 2:[2]
I guess that by using crontab, you're running your node app on a Linux machine so why don't you write a simple bash script ?
run_test.bash
#!/bin/bash
cd /path/to/your/app && \
npm run api-pro
then your crontab should look like :
0 * * * * /path/to/your/bash/script/run_test.bash
Of course, your script will have to be executable for your user :
$ chmod u+x run_test.bash
Solution 3:[3]
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:
- Print two things we will need
echo $PATH
// /opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:...
which npm
// /opt/homebrew/bin/npm
- Open crontab with
EDITOR="vim" crontab -e
- Add these two lines
PATH={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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | dun32 |
Solution 3 | KFunk |