Thursday, May 26, 2022

[SOLVED] Not able to use Node.js and Crontab

Issue

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

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.



Answered By - DrakaSAN
Answer Checked By - Willingham (WPSolving Volunteer)