title: Node.js: Easiest way to capture stdout into string variable
body: <p>I have the following code:</p>
  
  <pre><code>const spawn = require("child_process").spawn;
  
  const netStat = spawn('netstat', ['-nat']);
  const grepPort = spawn('grep', ['3000']);
  const grepStatus = spawn('grep', ['ESTABLISHED']);
  
  console.log('Determining public ip\'s connected to port 3000');
  
  // get port 3000 from netstat
  netStat.stdout.on('data', (data) =&gt; {
    grepPort.stdin.write(data);
    });
  
  netStat.on('close', (code) =&gt; {
    if (code !== 0) {console.log(`netstat process exited with code ${code}`);}
    grepPort.stdin.end();
  });
  
  // get ESTABLISHED from port 3000
  grepPort.stdout.on('data', (data) =&gt; {
    grepStatus.stdin.write(data);
    });
  
  grepPort.on('close', (code) =&gt; {
    grepStatus.stdin.end();
  });
  
  grepStatus.stdout.on('data', (data) =&gt; {
    console.log(data.toString())
    // Store data.toString() to variable here
  });
  </code></pre>
  
  <p>I am trying to capture the final data into a string where the comment is in the 3rd to last line. </p>
  
  <p>I've looked into streams, buffer objects, etc and got nothing to work (maybe I was doing them wrong?) so I'm looking for a fresh solution that will work or a simple "its not possible". </p>
  
  <p>EDIT:
  Lets say the code is revised:</p>
  
  <pre><code>const spawn = require("child_process").spawn;
  var port = 3000
  console.log(`Determining public ip\'s connected to port ${port}`);
  
  let output = '';
  
  const proc = spawn('sh', [
    '-c',
    `netstat -nat | grep ${port}.*ESTABLISHED | awk '{print $5}' | grep -v .*${port}`
  ]);
  
  proc.stdout.on('data', (chunk) =&gt; {
    output += chunk.toString();
  });
  
  proc.stderr.on('data', (chunk) =&gt; {
    console.log(chunk.toString());
  });
  
  proc.on('error', (err) =&gt; {
    console.error(err);
  });
  
  proc.on('exit', (code) =&gt; {
    console.log("Done");
  });
  
  console.log(output); // Should print output, no?
  </code></pre>
  
  <p>Thanks in advance for the help!</p>