How can you execute a Node.js script via a cron job?

Quite simply, I have node script that I want to execute once a month.

30 6 1 * * node /home/steve/example/script.js

But this doesn't work, presumably because of path or the shell the command is being ran under. I've tried the following means of executing node via cron (tested with -v):

steve@atom:~$ node -v
v0.4.2

steve@atom:~$ sh node -v
sh: Can't open node

steve@atom:~$ bash node -v
/usr/local/bin/node: /usr/local/bin/node: cannot execute binary file

steve@atom:~$ /usr/local/bin/node -v
v0.4.2

steve@atom:~$ sh /usr/local/bin/node -v
/usr/local/bin/node: 1: Syntax error: "(" unexpected

steve@atom:~$ bash /usr/local/bin/node -v
/usr/local/bin/node: /usr/local/bin/node: cannot execute binary file

I've ran out of ideas to try, any advice?


just provide the full path to node /usr/local/bin/node in your cron job like:

30 6 1 * * /usr/local/bin/node /home/steve/example/script.js

These answers here saying using absolute path will all cause major problems for running a larger node app!

Real Complete Solution

Edit Cron Jobs

crontab -e

Find Node Path

which node

CD into the destination folder, then Change Cron Job according to Node Path and run script

*/2 * * * * cd /home/destination/path && /bin/node index.js

This will then allow you to run a full NodeJS application without all the errors like how using an absolute path for your index.js file.


Additionally, just put #!/usr/local/bin/node at the top of the script you want to execute. Then it will automatically know to execute the script with node. Make sure the file is executable as well.


You can also specify paths to binary files on top of your user crontab like:

PATH=/bin:/usr/bin:/usr/local/bin

* * * * * cd your/path && node foo.js
* * * * * cd your/path && npm run bar