为什么这个node.js脚本不在crontab中运行?

为什么这个node.js脚本不在crontab中运行?,node.js,cron,crontab,Node.js,Cron,Crontab,如果我在包含的目录中运行node.js脚本,它会正常运行。如果我从crontab和 */1 * * * * /usr/local/bin/node /Users/full/path/to/main >> ~/mtf.log 我看到了与twilio配置相关的错误 var TWClient = require('twilio')(configTwilio.accountSid, configTwilio.

如果我在包含的目录中运行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和LocalHostOSX 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的配置目录中,包含修订的:

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

如果尝试将其包装到shell脚本中,则可以成功地在crontab条目中设置一些环境变量

请参见对类似问题的回答:


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

process.env.NODE_CONFIG_DIR=u dirname+'/CONFIG'


var config=require'config'

这是说“configTwilio”未定义,因此配置模块中的某些内容无法正常工作。。。猜测你的相对路径在那里不起作用。您可能需要先移动到正确的工作目录,它不会自动成为运行.js文件的来源。您的意思是编写一个shell脚本,首先更改目录,然后从cron运行该脚本吗?@codecowboy,请查看以获取调试该文件的提示和命令。@Joe我更新了我的问题。目录中的cd似乎没有帮助哇,@thatotherguy,你在crontab标签wiki上做了一个非常有用的编辑。恭喜!