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 3 years have passed since last update.

Node.js: stream.Readableを全部読み込む方法

Posted at

この投稿では、Node.jsのstream.Readableの内容を全部読み込む方法を紹介します。

stream.Readableを全部読み込む方法

for awaitを使う方法がシンプルです。

const { Readable } = require('stream')
const stream = Readable.from(['hello', 'world'])

async function readAll(stream) {
  let data = ''
  for await (const chunk of stream) {
    data += chunk
  }
  return data
}

readAll(stream).then(console.log)
//=> "helloworld"

イベント駆動なコード

よく見かける方法として、Readable"data"イベントを使うコードがあります:

const { Readable } = require('stream')
const stream = Readable.from(['hello', 'world'])

function readAll(stream) {
  return new Promise(resolve => {
    let data = ''
    stream.on('data', chunk => {
      data += chunk
    })
    stream.on('end', () => resolve(data))
  })
}

readAll(stream).then(console.log)
//=> "helloworld"

これでも同じ結果が得られますが、for awaitを使ったほうが個人的に読みやすいと思います。

関連記事

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?