IgorGanapolsky
IgorGanapolsky

Reputation: 26851

Node.js script not executing from crontab

I have a crontab entry that is supposed to execute a node.js script like this:

*/5 * * * * node /home/campaigns/reporting/UNIT_TESTS/testCron.js > /home/campaigns/reporting/UNIT_TESTS/cron.log

However, it doesn't execute and the log file isn't updated. When I run the script manually, everything works though. Any ideas??

Thank you, Igor

Upvotes: 7

Views: 27602

Answers (7)

maxxx
maxxx

Reputation: 736

Making soft links like this might be a solution for using node in crontab when it was installed with NVM:

$ sudo ln -s "$NVM_DIR/versions/node/$(nvm version)/bin/node" "/usr/local/bin/node"
$ sudo ln -s "$NVM_DIR/versions/node/$(nvm version)/bin/npm" "/usr/local/bin/npm"

Upvotes: 1

Michael Nelles
Michael Nelles

Reputation: 6032

Try to actually run the command from the promp > then hit the endpoint and look at the catch message.

For me step 1

/usr/bin/node /var/www/iiiiii.net/server.js

then hit the endpoint (or url) with browser or postman.

I had the following error because my config did not pick up .env credentials when being run off of crontab.

 Access denied for user ''@'localhost' (using password: NO)

It could be any number of errors - but if you test it in this way it will reveal your particular error.

Upvotes: 0

Vaibhaw K
Vaibhaw K

Reputation: 179

It's explained pretty well over here.

This can happen if your binary (node in this case) is under /usr/local/bin. By default, crontab looks for the binaries under /usr/bin or /bin.

Upvotes: 6

afacat
afacat

Reputation: 2748

I'm using nvm install node.js in Linux, and seems the crontab don't know the path well, so I wrote the full path of node to execute the node file.

* * * * * /home/www/.nvm/versions/node/v8.11.1/bin/node /home/www/ss-config/index.js

Upvotes: 9

Anconia
Anconia

Reputation: 4038

I recently ran in to this same problem and was able to solve it with the help of the below blog post.

Essentially, put the full path to node and your file in the cron job:

/usr/local/bin/node /var/www/coffee.js

http://www.themechanism.com/voice/2012/08/28/getting-node-js-and-cron-to-play-nicely/

Upvotes: 11

Alexey Kamenskiy
Alexey Kamenskiy

Reputation: 2948

I also had this problem. Seems that after system update on our server the link to node binary is gone from PATH. Therefore the best solution in this case is always use not node script.js, but full path to binary which in our case is /usr/local/bin/node script.js.

Upvotes: 19

Daniel
Daniel

Reputation: 31609

Try making a script with the command:

script.sh:

#!/usr/bin/env sh
node /home/campaigns/reporting/UNIT_TESTS/testCron.js > /home/campaigns/reporting/UNIT_TESTS/cron.log

and then adding that to cron:

*/5 * * * * /path/to/script.sh

make sure to make the script executable (chmod +x script.sh)

Upvotes: 9

Related Questions