LinuxまたはWindowsのシェルコマンドを実行して、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には200KBのバッファ制限があるchild_process.spawnため、を使用する必要がありchild_process.execます。
最終決議
ジェームズホワイトの答えを受け入れますが、これは私のために働いた正確なコードです...
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結果の先頭に。