0

If I run my node.js script in the containing directory, it runs fine. If I run it from crontab with

*/1 * * * * /usr/local/bin/node /Users/full/path/to/main >> ~/mtf.log

I see errors relating to the twilio config

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

Why doesn't this work when run from cron? The same behaviour occurs on the server (ubuntu) and localhost (OSX 10.8.5)

Top of script (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);

The config file default.yaml is in the config directory relative to main.js and contains (redacted):

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

Twilio:
  accountSid: AC8fxxxxxxxxd5f7aace47a8
  authToken:  d863b4ddfxxxxxx9b7c845

I've also tried this locally:

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

but get:

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
codecowboy
  • 9,835
  • 18
  • 79
  • 134
  • 1
    It's saying 'configTwilio' is undefined, so something in your `config` module isn't working... Guessing your relative path doesn't work there. You probably need to move to the correct working directory first (it will not automatically be where the .js file is run from.) – Joe Jan 31 '14 at 18:48
  • do you mean write a shell script which first changes directory and then run that script from cron? – codecowboy Jan 31 '14 at 19:09
  • @codecowboy, check out the [crontab tag wiki](http://stackoverflow.com/tags/crontab/info) for tips and commands to debug this. – that other guy Jan 31 '14 at 20:52
  • @Joe I updated my question. a cd into the directory does not seem to help – codecowboy Feb 01 '14 at 08:54
  • Wow, @thatotherguy, you made a very useful edit on the crontab tag wiki. Congrats! – fedorqui Feb 03 '14 at 13:36

2 Answers2

0

If you try wrapping it inside a shell script, you may have success with setting some environment variables in the crontab entry.

See this answer to a similar question:

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

Community
  • 1
  • 1
Marc Smith
  • 1,111
  • 10
  • 18
0

When you schedule a cron task, the node js won't identify the config json files in your local directory. Add the code below in your main.js file to change the node config directory.

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

var config = require('config');