我仍在尝试掌握如何运行linux或Windows shell命令并在node.js中捕获输出的细节。最终,我想做这样的事情...
//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()
无效吗?FWIW,我需要使用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);
me.stdout = "";
在cmd_exec()
防止串联undefined
到结果的开始。