はじめてのReadable Stream

そろそろstream2が出る(というか開発版はもうstream2使えるけど)のにstream1すら全然理解してないので、いろいろ調べつつ書いてみたのです。
いろんなものを読んでも読んでもさっぱりわからない……状態だったのですが、とりあえず実装してみて若干わかったような気がするので一応メモを書いておこうかと。

今回実装したReadable Stream

500ミリ秒置きに数字を出力するもの。ドキュメント通りに実装したつもり……

read.js
var stream = require('stream'),
    util = require('util');

function ReadStream() {
  var that = this;

  stream.Stream.call(this);
  this.readable = true;

  this.encoding = '';
  this.pause = false;

  this.count = 0;
  this.interval = setInterval(function() {
    var buffer;

    if (that.pause) {
      return;
    }

    if (that.count++ < 10) {
      buffer = new Buffer(that.count + '\n');
      that.emit('data',
          (that.encoding) ? buffer.toString(that.encoding) : buffer);
    } else {
      that.emit('end');
      that.readable = false;
      clearInterval(that.interval);
    }
  }, 500);
}

util.inherits(ReadStream, stream.Stream);

ReadStream.prototype.setEncoding = function(encoding) {
  this.encoding = encoding;
};

ReadStream.prototype.pause = function() {
  this.pause = true;
};

ReadStream.prototype.resume = function() {
  this.pause = false;
};

ReadStream.prototype.destroy = function() {
  this.emit('close');
  this.readable = false;
};

module.exports = {
  create: function() {
    return new ReadStream;
  }
};
index.js
var fs = require('fs'),
    readstream = require('./read'),
    rstream = readstream.create();

rstream.pipe(fs.createWriteStream('./out'));

実行してみる

$ node index.js

しばらくするとoutが出力されて、中身には

1
2
3
4
5
6
7
8
9
10

が出力されてます。


ファイルにはちゃんと出力されてたけど、これでいいのかすごく自信ないなあ……