title: How to pipe and save output of spawnSync process in Node.js?
body: <p>I spawn some command synchronously and want two things:</p>
  
  <ol>
  <li>Pipe its stdout to process.stdout.</li>
  <li>Save the stdout into variable.</li>
  </ol>
  
  <p>I’ve written this code:</p>
  
  <pre><code>var spawnSync = require('child_process').spawnSync;
  var result = spawnSync('ls', [ '-l', '-a' ]);
  var savedOutput = result.stdout;
  
  console.log(String(savedOutput));
  </code></pre>
  
  <p>So, I store stdout in savedOutput variable — it’s ok, and log it out. But I haven’t pipe it to stdout. If the spawned process is long and write strings one by one, I see empty screen a long time, and at the end I see whole stdout of process.</p>
  
  <p>I’ve add options for piping:</p>
  
  <pre><code>var spawnSync = require('child_process').spawnSync;
  var result = spawnSync('ls', [ '-l', '-a' ], {
      stdio: [ 'ignore', 1, 2 ]
  });
  var savedOutput = result.stdout;
  
  console.log(String(savedOutput));
  </code></pre>
  
  <p>Stdout of spawned process is piped to stdout — it’s ok. But result.stdout is empty.</p>
  
  <p>I’ve tried to use stream:</p>
  
  <pre><code>var spawnSync = require('child_process').spawnSync;
  var stream = require('stream');
  var grabber = new stream.Writable();
  
  grabber._write = function(chunk, enc, done) {
      console.log('Chunk:');
      console.log(String(chunk));
      done();
  };
  
  var result = spawnSync('ls', [ '-l', '-a' ], {
      stdio: [ 'ignore', grabber, 2 ]
  });
  </code></pre>
  
  <p>... but get an error:</p>
  
  <pre><code>internal/child_process.js:795
    throw new TypeError('Incorrect value for stdio stream: ' +
    ^
  
  TypeError: Incorrect value for stdio stream: Writable
  </code></pre>
  
  <p>If I set <code>grabber.fd = 2</code>, I don’t get an error, but child stdout pipes to stdout instead of grabber.</p>
  
  <p>So. How to save child stdout into variable and pipe it to stdout in the same time?</p>