我仍在努力掌握如何在 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()无效吗?FWIW,我需要使用child_process.spawn,因为child_process.exec有 200KB 缓冲区限制。
最终决议
我接受詹姆斯怀特的回答,但这是对我有用的确切代码......
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);