title: How to read an entire text stream in node.js?
body: <p>In RingoJS there's a <a href="http://ringojs.org/api/master/io/#TextStream.prototype.read" rel="noreferrer" title="io - Ringo master - RingoJS">function</a> called <code>read</code> which allows you to read an entire stream until the end is reached. This is useful when you're making a command line application. For example you may write a <code>tac</code> <a href="http://en.wikipedia.org/wiki/Tac_(Unix)" rel="noreferrer" title="tac (Unix) - Wikipedia, the free encyclopedia">program</a> as follows:</p>
  
  <pre><code>#!/usr/bin/env ringo
  
  var string = system.stdin.read(); // read the entire input stream
  var lines = string.split("\n");   // split the lines
  
  lines.reverse();                  // reverse the lines
  
  var reversed = lines.join("\n");  // join the reversed lines
  system.stdout.write(reversed);    // write the reversed lines
  </code></pre>
  
  <p>This allows you to fire up a shell and run the <code>tac</code> command. Then you type in as many lines as you wish to and after you're done you can press <kbd>Ctrl</kbd>+<kbd>D</kbd> (or <kbd>Ctrl</kbd>+<kbd>Z</kbd> on Windows) to signal the <a href="http://en.wikipedia.org/wiki/End-of-transmission_character" rel="noreferrer" title="End-of-transmission character - Wikipedia, the free encyclopedia">end of transmission</a>.</p>
  
  <p>I want to do the same thing in node.js but I can't find any function which would do so. I thought of using the <code>readSync</code> <a href="http://nodejs.org/api/fs.html#fs_fs_readsync_fd_buffer_offset_length_position" rel="noreferrer" title="File System Node.js v0.8.14 Manual &amp; Documentation">function</a> from the <code>fs</code> library to simulate as follows, but to no avail:</p>
  
  <pre><code>fs.readSync(0, buffer, 0, buffer.length, null);
  </code></pre>
  
  <p>The <a href="http://en.wikipedia.org/wiki/Standard_streams#Standard_input_.28stdin.29" rel="noreferrer" title="Standard streams - Wikipedia, the free encyclopedia">file descriptor for stdin</a> (the first argument) is <code>0</code>. So it should read the data from the keyboard. Instead it gives me the following error:</p>
  
  <pre><code>Error: ESPIPE, invalid seek
      at Object.fs.readSync (fs.js:381:19)
      at repl:1:4
      at REPLServer.self.eval (repl.js:109:21)
      at rli.on.self.bufferedCmd (repl.js:258:20)
      at REPLServer.self.eval (repl.js:116:5)
      at Interface.&lt;anonymous&gt; (repl.js:248:12)
      at Interface.EventEmitter.emit (events.js:96:17)
      at Interface._onLine (readline.js:200:10)
      at Interface._line (readline.js:518:8)
      at Interface._ttyWrite (readline.js:736:14)
  </code></pre>
  
  <p>How would you synchronously collect all the data in an input text stream and return it as a string in node.js? A code example would be very helpful.</p>