続・WritableStream
pipeしたときのpipeイベントをごにょごにょしなくても、いい感じにやってくれるみたい。
以下はソースコード。
wstream.js
var stream = require('stream'), util = require('util'); function WStream() { var that = this; stream.Stream.call(this); this.writable = true; this.source = null; this.once('pipe', function(src) { that.source = src; }); } util.inherits(WStream, stream.Stream); WStream.prototype.write = function(data, encoding) { var that = this; if (!this.writable) { this.emit('error', new Error('WStream not writable')); this.writable = false; return; } process.stdout.write(data, encoding); setTimeout(function() { that.emit('drain'); }, 500); return false; }; WStream.prototype.end = function(data, encoding) { if (data) { this.write(data, encoding); } this.destroy(); }; WStream.prototype.destroy = function() { this.writable = false; this.emit('close'); }; WStream.prototype.destroySoon = function() { this.destroy(); }; module.exports = { create: function() { return new WStream; } };
index.js
var fs = require('fs'), wstream = require('./wstream'), w = wstream.create(); fs.createReadStream('./wstream.js', { bufferSize: 16 }).pipe(w);
これを実行すると、wstream.jsの中身がちょこちょこ出力されるようになります。
一週間やってみて、まだまだ使いこなせてないけどそれなりにStreamがわかってきた気がする!