DEV Community

Riku Rouvila
Riku Rouvila

Posted on

How to easily read all data from a ReadableStream?

const chunks = [];
for await (let chunk of readable) {
  chunks.push(chunk);
}
console.log(Buffer.concat(chunks));
Enter fullscreen mode Exit fullscreen mode

Async iterator requires Node.js >=10.0.

So, for example, reading a file would be as easy as:

const fs = require("fs");

async function readFile(filename) {
  const readable = fs.createReadStream(filename);
  const chunks = [];
  for await (let chunk of readable) {
    chunks.push(chunk);
  }
  console.log(Buffer.concat(chunks).toString());
}

readFile("./tsconfig.json");
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
loige profile image
Luciano Mammino

A new way to do this (Node.js 16+) is by using the built-in stream/consumers library.

This one allows to easily accumulate binary data, JSON data and text data from any Readable stream

Still mostly unknown, but really convenient

Collapse
 
phi1ipp profile image
Philipp Grigoryev

You da man! Thank you so much, I was desperate to understand how to use this readable in Promise world