11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js: stream.Readableを作るシンプルな方法

Posted at

本稿では、どのようにしてNode.jsのstream.Readableを作ったらいいかを示す。

stream.Readableを作るサンプルコード

const { Readable } = require('stream')
const stream = Readable.from(['hello'])
stream.pipe(process.stdout)

実行結果

hello

説明

Readable.fromメソッドはReadableオブジェクトを生成するユーティリティメソッドで、第一引数にIterable<any>またはAsyncIterable<any>を取る。

上のサンプルコードではArray<string>を渡しているが、Iterable反復処理プロトコルを実装しているオブジェクトなら何でもいいので、配列の他にジェネレーターを渡すこともできる:

const gen = function *() {
	yield 'hello'
	yield 'world'
}
const stream = Readable.from(gen())
11
3
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
11
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?