title: node.js shell command execution
body: <p>I am still trying to grasp the finer points of how I can run a linux or windows shell command and capture output within node.js; ultimately, I want to do something like this...</p>
  
  <pre><code>//pseudocode
  output = run_command(cmd, args)
  </code></pre>
  
  <p>The important piece is that <code>output</code> must be available to a globally scoped variable (or object).  I tried the following function, but for some reason, I get <code>undefined</code> printed to the console...</p>
  
  <pre class="lang-js prettyprint-override"><code>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" &lt;------
  </code></pre>
  
  <p>I'm having trouble understanding where the code breaks above... a very simple prototype of that model works...</p>
  
  <pre class="lang-js prettyprint-override"><code>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" &lt;----
  </code></pre>
  
  <p>Can someone help me understand why <code>try_this()</code> works, and <code>run_cmd()</code> does not?  FWIW, I need to use <a href="http://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options" rel="noreferrer"><code>child_process.spawn</code></a>, because <a href="http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback" rel="noreferrer"><code>child_process.exec</code></a> has a 200KB buffer limit.</p>
  
  <h2>Final Resolution</h2>
  
  <p>I'm accepting James White's answer, but this is the exact code that worked for me...</p>
  
  <pre><code>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);
  </code></pre>