Executing shell script from code
Try this
// app.jsrequire('child_process').spawn('sh', ['test.sh'], {stdio: 'inherit'});
The code works for me perfectly, without any changes. When you say you are not able to see any response, does the process hang? what is the final outcome? I doubt the sudo command in the script is causing some issues. Can you eliminate that and change? I don't have sudo access, so it failed on prompt.
bash-4.1$ node app.js[sudo] password for gireesh:[sudo] password for gireesh:[sudo] password for gireesh:[Error: Error: Command failed: /bin/sh -c sh test.sh--2016-04-27 08:28:01-- http://nodejs.org/dist/v0.10.26/node-v0.10.26-linux-x64.tar.gzResolving nodejs.org... 104.20.22.46, 104.20.23.46, 2400:cb00:2048:1::6814:172e, ...Connecting to nodejs.org|104.20.22.46|:80... connected.HTTP request sent, awaiting response... 200 OKLength: 5314716 (5.1M) [application/octet-stream]Saving to: ânode-v0.10.26-linux-x64.tar.gz.2â
Some diagnostic steps:
- Print the child object, after the excec call. This will print the process information pertinent to the child. This will make sure the child is started.
- Install a child terminator callback, and print a debug information in it. This will make sure the child is ended.
- If still problem persists, install child stream hooks. This will make sure the instantaneous prints in the streams are output immediately, rather than at the end.
Modified exec_process.js
var exec = require('child_process').exec;var result = function(command, cb){ var child = exec(command, function(err, stdout, stderr){ if(err != null){ return cb(new Error(err), null); }else if(typeof(stderr) != "string"){ return cb(new Error(stderr), null); }else{ return cb(null, stdout); } }); console.log(child); child.on('close', function(code) { console.log('child ended with: ' + code); }); child.on('error', function(err) { console.log('child errd with: ' + err); }); child.stdout.on('data', function(d) { console.log('child stdout: ' + d); });}exports.result = result;
Hope this helps.