DEV Community

loading...

How to easily read all data from a ReadableStream?

rikurouvila profile image Riku Rouvila ・1 min read
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

Discussion

pic
Editor guide