概要
二つのStreamを作ってpipeでつなぎます。
- 配列からStreamを作るArrayStream
- 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)
入出力にオブジェクトを使いたいので、objectMode
をtrue
に設定します。
デフォルトはBufferです。
準備
npm install -g babel
実行
babel-node index.js
結果
1
2
3
4