【问题标题】:Why does this node.js script not run in crontab?为什么这个 node.js 脚本不在 crontab 中运行?
【发布时间】:2018-12-03 15:25:00
【问题描述】:

如果我在包含目录中运行我的 node.js 脚本,它运行良好。如果我使用

从 crontab 运行它
*/1 * * * * /usr/local/bin/node /Users/full/path/to/main >> ~/mtf.log

我看到与 twilio 配置相关的错误

var TWClient        = require('twilio')(configTwilio.accountSid, configTwilio.
                                                ^
TypeError: Cannot read property 'accountSid' of undefined

为什么从 cron 运行时这不起作用?服务器(ubuntu)和本地主机(OSX 10.8.5)上发生相同的行为

脚本顶部(main.js)

var phantom         = require('phantom');
var portscanner     = require('portscanner');
var FeedParser      = require('feedparser'),
    request         = require('request');
var configDB        = require('config').DB;
var configTwilio    = require('config').Twilio;
var mysql           = require('mysql');

var TWClient        = require('twilio')(configTwilio.accountSid, configTwilio.authToken);

配置文件 default.yaml 位于相对于 main.js 的 config 目录中,包含(已编辑):

DB:
  dbHost: localhost
  dbPort: 3306
  dbName: xxx
  dbUser: xxx
  dbPass: xxx

Twilio:
  accountSid: AC8fxxxxxxxxd5f7aace47a8
  authToken:  d863b4ddfxxxxxx9b7c845

我也在本地尝试过:

env -i sh -c 'cd /path/to/script && /usr/local/bin/node main'

但得到:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT

【问题讨论】:

  • 它说 'configTwilio' 是未定义的,所以你的 config 模块中的某些东西不起作用......猜测你的相对路径在那里不起作用。您可能需要先移动到正确的工作目录(它不会自动成为运行 .js 文件的位置。)
  • 你的意思是写一个shell脚本,首先改变目录,然后从cron运行那个脚本?
  • @codecowboy,查看crontab tag wiki 获取调试提示和命令。
  • @Joe 我更新了我的问题。 cd 进入目录似乎没有帮助
  • 哇,@thatotherguy,您在 crontab 标签 wiki 上进行了非常有用的编辑。恭喜!

标签: node.js cron crontab


【解决方案1】:

如果您尝试将其包装在 shell 脚本中,您可能会成功在 crontab 条目中设置一些环境变量。

查看类似问题的答案:

https://stackoverflow.com/a/27823675/608269

【讨论】:

    【解决方案2】:

    当你安排一个 cron 任务时,node js 不会识别你本地目录中的 config json 文件。在您的 main.js 文件中添加以下代码以更改节点配置目录。

    process.env.NODE_CONFIG_DIR= __dirname +'/config';

    var config = require('config');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      相关资源
      最近更新 更多