Skip to content

Latest commit

 

History

History
58 lines (44 loc) · 1.15 KB

File metadata and controls

58 lines (44 loc) · 1.15 KB
description Modern alternatives to the get-stream package

Replacements for get-stream

Converting stream to string

You can convert a stream to a string by using Buffer.from and a for await:

async function streamToString(stream) {
  const chunks = []
  for await (const chunk of stream) {
    chunks.push(Buffer.from(chunk))
  }
  return Buffer.concat(chunks).toString('utf-8')
}

Converting stream to Array

You can convert a stream to an array using Array.fromAsync:

await Array.fromAsync(stream)

// or before Node 22

async function streamToArray(stream) {
  const chunks = []
  for await (const chunk of stream) {
    chunks.push(chunk)
  }
  return chunks
}

Converting stream to Buffer

You can convert a stream to a Buffer using Array.fromAsync with a mapper:

async function streamToBuffer(stream) {
  const chunks = await Array.fromAsync(stream, (chunk) => Buffer.from(chunk))
  return Buffer.concat(chunks)
}

// or before Node 22

async function streamToBuffer(stream) {
  const chunks = []
  for await (const chunk of stream) {
    chunks.push(Buffer.from(chunk))
  }
  return Buffer.concat(chunks)
}