title: Piping data from child to parent in nodejs
body: <p>I have a nodejs parent process that starts up another nodejs child process. The child process executes some logic and then returns output to the parent. The output is large and I'm trying to use pipes to communicate, as suggested in documentation for child.send() method (which works fine BTW). </p>
  
  <p>I would like someone to suggest how to properly build this communication channel. I want to be able to send data from parent to child and also to be able to send data from child to parent. I've started it a bit, but it is incomplete (sends message only from parent to child) and throws an error. </p>
  
  <p>Parent File Code:</p>
  
  <pre><code>var child_process = require('child_process');
  
  var opts = {
      stdio: [process.stdin, process.stdout, process.stderr, 'pipe']
  };
  var child = child_process.spawn('node', ['./b.js'], opts);
  
  require('streamifier').createReadStream('test 2').pipe(child.stdio[3]);
  </code></pre>
  
  <p>Child file code:</p>
  
  <pre><code>var fs =  require('fs');
  
  // read from it
  var readable = fs.createReadStream(null, {fd: 3});
  
  var chunks = []; 
  
  readable.on('data', function(chunk) {
      chunks.push(chunk);
  });
  
  readable.on('end', function() {
      console.log(chunks.join().toString());
  })
  </code></pre>
  
  <p>The above code prints expected output ("test 2") along with the following error:</p>
  
  <pre><code>events.js:85
        throw er; // Unhandled 'error' event
              ^
  Error: shutdown ENOTCONN
      at exports._errnoException (util.js:746:11)
      at Socket.onSocketFinish (net.js:232:26)
      at Socket.emit (events.js:129:20)
      at finishMaybe (_stream_writable.js:484:14)
      at afterWrite (_stream_writable.js:362:3)
      at _stream_writable.js:349:9
      at process._tickCallback (node.js:355:11)
      at Function.Module.runMain (module.js:503:11)
      at startup (node.js:129:16)
      at node.js:814:3
  </code></pre>
  
  <hr>
  
  <p>Full Answer:</p>
  
  <p>Parent's code:</p>
  
  <pre><code>var child_process = require('child_process');
  
  var opts = {
      stdio: [process.stdin, process.stdout, process.stderr, 'pipe', 'pipe']
  };
  var child = child_process.spawn('node', ['./b.js'], opts);
  
  child.stdio[3].write('First message.\n', 'utf8', function() {
      child.stdio[3].write('Second message.\n', 'utf8', function() {
  
      });
  }); 
  
  child.stdio[4].pipe(process.stdout);
  </code></pre>
  
  <p>Child's code:</p>
  
  <pre><code>var fs =  require('fs');
  
  // read from it
  var readable = fs.createReadStream(null, {fd: 3});
  
  readable.pipe(process.stdout);
  fs.createWriteStream(null, {fd: 4}).write('Sending a message back.');
  </code></pre>