【发布时间】:2013-01-05 16:19:59
【问题描述】:
我仍在尝试掌握如何运行 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);
【问题讨论】:
-
在最终分辨率中,您应该在
cmd_exec()中设置me.stdout = "";,以防止将undefined连接到结果的开头。 -
嘿,最终解析代码太糟糕了,如果执行 netstat 的时间超过 0.25 秒怎么办?
-
Ummmm...也许使用我奖励给的答案之一??????
标签: javascript node.js shell