使用 node.js (childProcess) 运行 shell 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19103735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run shell script with node.js (childProcess)
提问by Ralf
I want to run a shell script on my node.js server, but nothing happened...
我想在我的 node.js 服务器上运行一个 shell 脚本,但什么也没发生......
childProcess.exec('~/./play.sh /media/external/' + req.params.movie, function() {}); //not working
Another childProcess works perfect, but the process above won't.
另一个 childProcess 工作完美,但上面的过程不会。
childProcess.exec('ls /media/external/', movieCallback); //works
If I run the script in terminal, then it works. Any ideas? (chmod +x is set)
如果我在终端中运行脚本,那么它就可以工作。有任何想法吗?(chmod +x 设置)
回答by smokey.edgy
The exec function callback has error, stdout and stderr arguments passed to it. See if they can help you diagnose the problem by spitting them out to the console:
exec 函数回调有传递给它的错误、标准输出和标准错误参数。看看他们是否可以通过将它们吐出到控制台来帮助您诊断问题:
exec('~/./play.sh /media/external/' + req.params.movie,
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
回答by n_rao
exec('sh ~/play.sh /media/external/' + req.params.movie ,function(err,stdout,stderr){
console.log(err,stdout,stderr);
})
Runs your play.shshellscript with /media/external/+req.params.movie as argument. The output is available through stdout,stderr variables in the callback.
play.sh使用/media/external/+req.params.movie 作为参数运行您的shellscript。输出可通过回调中的 stdout,stderr 变量获得。
OR TRY THIS
或者试试这个
var myscript = exec('sh ~/play.sh /media/external/' + req.params.movie);
myscript.stdout.on('data',function(data){
console.log(data); // process output will be displayed here
});
myscript.stderr.on('data',function(data){
console.log(data); // process error output will be displayed here
});`

