Rhushikesh Rhushikesh - 4 months ago 14
Node.js Question

How to execute the file at different location in nodejs

I have to run file test.js which is at different location than the my running application. To do that i have tried the fallowing code

var execFile = require("child_process").execFile;
exports.sync = function(req, res) {
console.log("sync called");
var child = execFile("C:/Users/rhush/Desktop/test", function(error, stdout, stderr) {
if (error) {
throw error;
}
console.log(stdout);
res.send({ status: stdout });
});
};


and my test file is here :

function testing() {
console.log('sync job running');
}
testing();


but i got the error enter image description here

please correct if i am doing any mistake.

Answer

To run a js file using execFile you need to pass node command with file name, Use this one:

var execFile = require("child_process").execFile;
exports.sync = function(req, res) {
    console.log("sync called");

    var child = execFile("node", ["C:/Users/rhush/Desktop/test.js"], function(error, stdout, stderr) {
        if (error) {
            throw error;
        }
        res.send({ status: stdout });
    });
};