Bryce Johnson
Bryce Johnson

Reputation: 6931

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.

Upvotes: 10

Views: 10446

Answers (3)

Marsh3423
Marsh3423

Reputation: 1

You could try running the bash file directly from the cron?

i.e.

0 4 * * * source ~/.bashrc && cd /projects/my-project && node index.js

Upvotes: 0

Tigertron
Tigertron

Reputation: 638

I had the exact same problem, so I ended creating a passthrough script that would load my environment variables, then execute node like so:

##!/bin/bash

# Source bash profile to load env variables
# or any other that you want to set explicitly
. ~/.bash_profile

# tunnel that allows us to execute cron jobs
node $1 $2

To use just add it to your crontab

* * * * * <user> <passthrough_script> <arg1> <arg2>

Upvotes: 3

Marc Smith
Marc Smith

Reputation: 1121

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.

Upvotes: 17

Related Questions