Cron run Nodejs Not working

2019-09-10 18:44发布

问题:

I need to run a sh script send.sh as content shown below:

node send.js -q 8435924032 >> send.log

If I run it with crontab as */2 * * * * /home/app/send.sh nothing is outputed.

And there is a mail which shows an error thrown by the cron process:

ReferenceError: Promise is not defined
    at requestURL (/home/app/getData.js:34:16)
    at Object.getData (/home/app/getData.js:15:18)
    at /home/app/send.js:173:41
    ...

However it gives me correct output and NO ERROR when I directly run sh send.sh

Can someone helps? I want to run the program every two minutes. I tried PM2 but such cron feature is not working.

回答1:

Did you check the user root node.js version?

Crontab runs shell script as root by default, that means it's using the root user node.js instead of the node version which you are using to run the script.

Promise is not supported in older version of node.js.

If you have root privilege, you can check root user node.js version by,

$sudo su
$node -v

or, in your node.js script,

console.log(process.versions); //which contains running node version


回答2:

Make some modifications to your shell file:

Use Absolute path to file

node /<path>/<to>/<file>/send.js -q 8435924032 >> send.log

Or navigate to your directory

cd /<path>/<to>/<file>/;
node ./send.js -q 8435924032 >> send.log