我仍在努力掌握如何在node.js中运行Linux或Windows shell命令并捕获输出的细节;最终,我想做类似这样的事情...
//pseudocode
output = run_command(cmd, args)
重要的一点是output
必须可用于全局作用域变量(或对象)。我尝试了下面的函数,但由于某种原因,我在控制台上得到了undefined
...
function run_cmd(cmd, args, cb) {
var spawn = require('child_process').spawn
var child = spawn(cmd, args);
var me = this;
child.stdout.on('data', function(me, data) {
cb(me, data);
});
}
foo = new run_cmd('dir', ['/B'], function (me, data){me.stdout=data;});
console.log(foo.stdout); // yields "undefined" <------
我不太明白代码在哪里出了问题...一个非常简单的该模型的原型是有效的...
function try_this(cmd, cb) {
var me = this;
cb(me, cmd)
}
bar = new try_this('guacamole', function (me, cmd){me.output=cmd;})
console.log(bar.output); // yields "guacamole" <----
有人能帮我理解为什么try_this()
可以工作而run_cmd()
不能吗?顺便说一下,我需要使用child_process.spawn
,因为child_process.exec
有200KB的缓冲限制。
最终解决方案
我接受了James White的答案,但这是对我有效的确切代码...
function cmd_exec(cmd, args, cb_stdout, cb_end) {
var spawn = require('child_process').spawn,
child = spawn(cmd, args),
me = this;
me.exit = 0; // Send a cb to set 1 when cmd exits
me.stdout = "";
child.stdout.on('data', function (data) { cb_stdout(me, data) });
child.stdout.on('end', function () { cb_end(me) });
}
foo = new cmd_exec('netstat', ['-rn'],
function (me, data) {me.stdout += data.toString();},
function (me) {me.exit = 1;}
);
function log_console() {
console.log(foo.stdout);
}
setTimeout(
// wait 0.25 seconds and print the output
log_console,
250);
cmd_exec()
中设置me.stdout = "";
以防止将undefined
连接到结果的开头。 - aorcsik