node.js child process change a directory and run the process

com picture com · Sep 12, 2014 · Viewed 10.8k times · Source

I try to run external application in node.js with child process like the following

var cp = require("child_process");
cp.exec("cd "+path+" && ./run.sh",function(error,stdout,stderr){
})

However when I try to run it stuck, without entering the callback

run.sh starts a server, when I execute it with cp.exec I expect it run asynchronously, such that my application doesn't wait until server termination. In callback I want to work with server.

Please help me to solve this.

Answer

Boris Kirov picture Boris Kirov · Sep 12, 2014

cp.exec get the working directory in parameter options http://nodejs.org/docs/latest/api/child_process.html#child_process_child_process_exec_command_options_callback

Use

var cp = require("child_process");

cp.exec("./run.sh", {cwd: path}, function(error,stdout,stderr){
});

for running script in the "path" directory.