Readable-stream

04/22/2014, Tue
Categories: #JavaScript
Tags: #NodeJs

Streaming Consistency

Since Node's streaming Api is still changing and is in 'unstable' category, writing a npm module using streams may cause some unexpected behaviors on older versions of Node. To ensure that streams are compatible with older versions of Node, a drop-in replacement for stream is available called 'readable-stream'.

The following example uses the 'readable' event, which is not present on Node versions < 0.10, but the readable-stream module is handling this inconsistency which means that this example will work with Node versions < 0.10.

// Wrapping fs.createReadStream

var fs = require("fs"),
  Readable = require("readable-stream").Readable,
  reader = new Readable();

reader
  .wrap(fs.createReadStream("./test.txt"))
  .on("readable", function () {
    console.log(this.read().toString());
  })
  .on("end", function () {
    console.log("Finished reading stream");
  });