Search code examples
node.jscron

Why won't cron execute my node.js script?


I want my server to execute a node script every minute. The program executes perfectly if I execute the file manually (./main.js), so I'm pretty sure it's not the problem. But when I hand it over to cron to execute, nothing happens.

Here's the line from the cron file.

*/1 * * * * /home/bryce/scripts/wudu/main.js

And here's a sample log:

Oct 11 15:21:01 server CROND[2564]: (root) CMD (/home/bryce/scripts/wudu/main.js)

The executable: home/bryce/scripts/wudu/main.js

#!/usr/bin/env node

var program = require('commander');
var v = require('./cli/validation');
var a = require('./cli/actions');

program
  .version('0.0.1')
  .option('-u, --url', 'Register url')
  .option('-s, --selector', 'Register selector')
  .option('-p, --pagination', 'Register pagination')
  .option('-i, --index', 'Pass an index, to destroy')
  .parse(process.argv);

var args = process.argv.slice(2),
        mode = v.mode(args[0]),
        options = v.hasArgs(mode, program);

a.init(mode, options);

Any idea why I'm getting radio silence? Somewhere else I should be looking to debug?

UPDATE:

I believe the problem has to do with my relative filepaths, and main.js being executed from outside its own directory.

So now, I've placed exe.sh in the wudu directory. It looks like this:

#!/bin/bash

cd ${0%/*}
./main.js mail

exit

Now, I've set cron to execute this file every minute. I tried executing this file from other folders, and it works as expected. But again, cron isn't picking it up.


Solution

  • Wrapping the execution in a shell script, it's likely the execution of the script in cron doesn't have the same environment set as when you run from the command line.

    Try prefacing the execution of the shell script in cron with setting NODE_PATH & PATH
    (if you need these values, on a command line type: echo $NODE_PATH and echo $PATH)

    So, your cron entry would look like:

    */1 * * * * NODE_PATH=/usr/local/lib/node_modules PATH=/opt/local/bin:ABC:XYZ /home/bryce/scripts/wudu/exe.sh
    

    Just make sure to substitute the actual values for NODE_PATH & PATH with what you get from the echo commands that you first did.