Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run node script from within a node script

Tags:

shell

node.js

I would like to use node-schedule to run a certain node script at a certain time. Can I do something like this in node.js?

var schedule = require('node-schedule');

//https://www.npmjs.com/package/node-schedule
var j = schedule.scheduleJob('00 00 22 * * *', function () {
    console.log('Running XX node.js script ...');

    NodeShell.run(__dirname + '\\XX.js', function (err) {
        if (err) throw err;
        console.log('finished');
    });
});

Not sure if something like NodeShell exists. Other alternatives would be welcomed.

like image 823
guagay_wk Avatar asked Jul 01 '26 09:07

guagay_wk


1 Answers

You have several options, all of which are listed in the docs for child_process. Briefly:

  • child_process.exec spawns a shell
  • child_process.fork forks a node process
  • child_process.spawn spawns a process

For your case, to run a node script you could use something like this:

var childProcess = require("child_process");
var path = require("path");
var cp = childProcess.fork(path.join(__dirname, "xx.js"));
cp.on("exit", function (code, signal) {
    console.log("Exited", {code: code, signal: signal});
});
cp.on("error", console.error.bind(console));
like image 155
ZachB Avatar answered Jul 04 '26 17:07

ZachB