nodejs v4移行のstreamの書き方の記事が少ないので覚書
nodejs v0.x ES5時代
prototype拡張一択しかなく表記が冗長なのでthrough2
を使う事が多かった
var Transform = require('stream').Transform;
var util = require('util')
util.inherits(NewStream, Transform);
function NewStream(options){
Transform.call(this, options);
}
NewStream.prototype._transform = function(chunk, enc, cb){
// hogehoge
this.push(chunk);
cb();
}
var th = new NewStream(opt);
var through = require('through2')
var th = through.obj(function transform(chunk, enc, cb){
// hogehoge
this.push(chunk);
cb();
})
nodejs v4.x以降 ES6時代
Constructor APIが使えるようになったためthrough2
に頼る必要がなくなった
クラス構文とちがい_
は不要。
言うまでもないけどついアローファンクションを使ってthis.push
できないやらかしがあるので注意。
'use strict';
const Transform = require('stream').Transform;
let th = Transform({objectMode:true,
transform: function(chunk, enc, cb){
// hogehoge
this.push(chunk)
cb();
}
})
クラス構文でかけるようにもなった。
class NewStream extends Transform {
constructor(opt){
super(opt);
}
_transform(chunk, enc, cb){
// hogehoge
this.push(chunk)
cb();
}
}
これでstreamが捗りますね!