LoginSignup
3
1

More than 3 years have passed since last update.

Node.js: stream.Readableのデータの前後にデータを追加する方法

Posted at

Node.jsのstream.Readableのデータの前後にデータを追加する方法を紹介する。

const { Readable } = require('stream')

// 元データのストリーム
const source = Readable.from(['source content\n'])

// 元データの前後にデータを追加する処理(ジェネレーターを使う)
const wrap = (stream) => (async function *() {
    yield 'prepended content\n'
    yield* stream[Symbol.asyncIterator]()
    yield 'appended content\n'
})()

// データが追加されたストリーム
const wrappedContent = Readable.from(wrap(source))
wrappedContent.pipe(process.stdout)

実行結果

prepended content
source content
appended content

stream.Readableには当然ながらwriteメソッドが生えていないので、Readableオブジェクトを初期化する段階で加工済みのデータを渡してやる必要がある。

しかし、ストリームの内容をすべてバッファに入れると、メモリーを消費したりと、ストリーム処理ではなくなっていまうので、ジェネレーターを使う。

3
1
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
3
1