Skip to content

Instantly share code, notes, and snippets.

@lambrospetrou
Last active May 22, 2024 05:20
Show Gist options
  • Save lambrospetrou/0c9ac9da14d8d241ae3634981ceb2871 to your computer and use it in GitHub Desktop.
Save lambrospetrou/0c9ac9da14d8d241ae3634981ceb2871 to your computer and use it in GitHub Desktop.
// Option 1
async function streamToString(stream: NodeJS.ReadableStream): Promise<string> {
const chunks: Array<any> = [];
for await (let chunk of stream) {
chunks.push(chunk)
}
const buffer = Buffer.concat(chunks);
return buffer.toString("utf-8")
}
// Option 2
function streamToString2(stream: NodeJS.ReadableStream): Promise<string> {
const chunks: Array<any> = []
return new Promise((resolve, reject) => {
stream.on('data', chunk => chunks.push(chunk))
stream.on('error', reject)
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
})
}
@sdzialowski-godaddy
Copy link

sdzialowski-godaddy commented Aug 14, 2023

Above didn't work but other version did work:

async function streamToString(stream: any) {
  const reader = stream.getReader();
  const textDecoder = new TextDecoder();
  let result = '';

  async function read() {
    const { done, value } = await reader.read();

    if (done) {
      return result;
    }

    result += textDecoder.decode(value, { stream: true });
    return read();
  }

  return read();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment