LoginSignup
21
20

More than 5 years have passed since last update.

Node Stream APIを実装するサンプル

Last updated at Posted at 2015-05-10

概要

二つのStreamを作ってpipeでつなぎます。

  1. 配列からStreamを作るArrayStream
  2. Streamを出力するLogStream

RxJSのとても短いサンプルNode Stream版です。

動作環境

  • Node.js v0.12.2
  • babel.js 5.2.17

ソースコード

index.js
import {
  Writable,
  Readable
}
from 'stream'

const option = {
  objectMode: true
}

class ArrayStream extends Readable {
  constructor(array) {
    super(option)
    this._array = array
  }
  _read() {
    this.push(this._array.shift() || null)
  }
}

class LogStream extends Writable {
  constructor() {
    super(option)
  }
  _write(chunk, encoding, callback) {
    console.log(chunk)
    callback()
  }
}

new ArrayStream([1, 2, 3, 4])
  .pipe(new LogStream)

入出力にオブジェクトを使いたいので、objectModetrueに設定します。
デフォルトはBufferです。

準備

npm install -g babel

実行

babel-node index.js

結果

1
2
3
4

参考

21
20
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
21
20