LoginSignup
5
4

More than 5 years have passed since last update.

nodejs streamAPI覚書(ES6)

Last updated at Posted at 2016-01-22

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が捗りますね!

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4