title: Node pipe to stdout -- how do I tell if drained?
body: <p>The standard advice on determine whether you need to wait for <code>drain</code> event on <code>process.stdout</code> is to check whether it returns false when you write to it.</p>
  
  <p>How should I check if I've piped another stream to it? It would seem that that stream can emit <code>finish</code> before all the output is actually written. Can I do something like?</p>
  
  <pre><code>upstreamOfStdout.on('finish', function(){
    if(!process.stdout.write('')) {
      process.stdout.on('drain', function() { done("I'm done"); });
    }
    else {
      done("I'm done"); 
    }
  });
  upstreamOfStdout.pipe(process.stdout);
  </code></pre>
  
  <p>I prefer an answer that doesn't depend on the internals of any streams. Just given that the streams conform to the node stream interface, what is the canonical way to do this?</p>
  
  <p><strong>EDIT</strong>: </p>
  
  <p>The larger context is a wrapper:</p>
  
  <pre><code>new Promise(function(resolve, reject){
    stream.on(&lt;some-event&gt;, resolve);
    ... (perhaps something else here?)
  });
  </code></pre>
  
  <p>where <code>stream</code> can be <code>process.stdout</code> or something else, which has another through stream piped into it.</p>
  
  <p>My program exits whenever <code>resolve</code> is called -- I presume the <code>Promise</code> code keeps the program alive until all promises have been resolved.</p>
  
  <p>I have encountered this situation several times, and have always used hacks to solve the problem (e.g. there are several private members in <code>process.stdout</code> that are useful.) But I really would like to solve this once and for all (or learn that it is a bug, so I can track the issue and fix my hacks when its resolved, at least): how do I tell when a stream downstream of another is finished processing its input?</p>