我正在尝试从nodejs代码
执行shell脚本//test.sh
wget http://nodejs.org/dist/v0.10.26/node-v0.10.26-linux-x64.tar.gz
tar -zxvf node-v0.10.26-linux-x64.tar.gz
mv node-v0.10.26-linux-x64 node-v0.10.26
sudo cp -r node-v0.10.26 /usr/local/src
//app.js
var exec = require('child_process').exec;
var execProcess = require("./exec_process.js");
execProcess.result("sh test.sh", function(err, response){
if(!err){
console.log(response);
}else {
console.log(err);
}
});
//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);
}
});
}
exports.result = result;
执行app.js后,我无法看到任何响应。我在这里做错了什么?
答案 0 :(得分:12)
试试这个
// app.js
require('child_process').spawn('sh', ['test.sh'], {stdio: 'inherit'});
答案 1 :(得分:1)
代码对我来说非常合适,没有任何变化。当您说您无法看到任何响应时,该过程是否会挂起?最终的结果是什么?我怀疑脚本中的sudo命令是否会导致一些问题。你能消除它并改变吗?我没有sudo访问权限,所以它在提示时失败了。
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.gz
Resolving 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 OK
Length: 5314716 (5.1M) [application/octet-stream]
Saving to: ânode-v0.10.26-linux-x64.tar.gz.2â
一些诊断步骤:
修改了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;
希望这有帮助。