为什么cron不正确执行我的node.js脚本?
我正在尝试从cron运行node.js脚本。它应该读取.json文件,进行API调用,然后写入.json-file的响应。
手动执行时,一切正常。
这确实是工作
sudo node ~/bots/gtaa/index.js
sudo crontab -e
29 9 * * 1-5 /usr/bin/node ~/bots/gtaa/index.js >> ~/gtaa-bot.log 2>&1
grep cron/var/var/log/syslog
May 11 09:29:01 raspberrypi CRON[54381]: (root) CMD (/usr/bin/node ~/bots/gtaa/index.js >> ~/gtaa-bot.log 2>&1)
我的index.js使用local .env-文件
require('dotenv').config({ path: __dirname + '/.env' })
也有 no gtaa-bot.log
-file在主目录中。
提出了一个非常类似的问题在这里假如。
I am trying to run a node.js script from cron. It is supposed to read a .json-File, make an API call and then write the response to a .json-File.
When executing manually everything works fine.
This does it's job
sudo node ~/bots/gtaa/index.js
sudo crontab -e
29 9 * * 1-5 /usr/bin/node ~/bots/gtaa/index.js >> ~/gtaa-bot.log 2>&1
grep cron /var/log/syslog
May 11 09:29:01 raspberrypi CRON[54381]: (root) CMD (/usr/bin/node ~/bots/gtaa/index.js >> ~/gtaa-bot.log 2>&1)
My index.js uses the local .env-File
require('dotenv').config({ path: __dirname + '/.env' })
There also is no gtaa-bot.log
-File in the home directory.
A very similar question has been asked here but there are no useful answers provided.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我经历了这个问题,最近使用Ubuntu 20.04.4 LTS
最终发生的事情是Cron在不同的环境中运行,并且很可能无法找到正确的节点途径。
有一些方法可以配置这一点,但是我发现一个更容易的解决方案最终只是让Cron执行一个运行NVM和/或节点的bash脚本。
例如,我有此设置每20分钟运行一次:
在我的
nvm_cron.sh.sh
文件中:不要忘记确保
nvm_cron.sh.sh
文件是可执行的以这种方式,我可以控制要为脚本运行的节点的版本,而不必担心会弄乱cron。
Well I have experienced this issue, more recently using Ubuntu 20.04.4 LTS
Ultimately what ends up happening is cron runs in a different environment and most likely is unable to find the correct path to node.
There are some ways to configure this, however I found a much easier solution ended up being to just have cron execute a bash script, that runs nvm and/or node.
For example, I have this setup to run every 20 minutes:
And in my
nvm_cron.sh
file:Dont forget to make sure the
nvm_cron.sh
file is executableThis way I have control over the version of node that I want to run for the script, and don't have to worry about messing with cron.