Read Streams With a Byte Limit

Read an async iterable stream into a string while enforcing a hard byte ceiling and destroying the source as soon as it overflows.

JavascriptSecurity Boundaries

Code

javascriptsnippet
36 lines
import { Buffer } from "node:buffer";
import { Readable } from "node:stream";

export async function readStreamWithLimit(stream, maxBytes, options = {}) {
  if (stream === null || typeof stream !== "object" || typeof stream[Symbol.asyncIterator] !== "function") {
    throw new TypeError("stream must be an async iterable readable stream");
  }
  if (!Number.isInteger(maxBytes) || maxBytes < 1) {
    throw new RangeError("maxBytes must be a positive integer");
  }
  const { encoding = "utf8" } = options;
  const chunks = [];
  let total = 0;
  try {
    for await (const chunk of stream) {
      const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
      total += buffer.length;
      if (total > maxBytes) {
        if (typeof stream.destroy === "function") stream.destroy();
        throw new Error(`stream exceeded the ${maxBytes} byte limit`);
      }
      chunks.push(buffer);
    }
  } finally {
    if (typeof stream.destroy === "function" && !stream.destroyed) stream.destroy();
  }
  return Buffer.concat(chunks).toString(encoding);
}

const body = Readable.from(["hello ", "world"]);
console.log(await readStreamWithLimit(body, 64));
try {
  await readStreamWithLimit(Readable.from(["0123456789"]), 4);
} catch (error) {
  console.log(error.message);
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

hello world
stream exceeded the 4 byte limit

Inside the snippet

Read Streams With a Byte Limit is built around the function readStreamWithLimit.

Repetition is confined to for await (const chunk of stream) — the rest of the file is straight-line. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The only import source is node:buffer, node:stream, a Node.js built-in, exposing Buffer, Readable. The code refuses to proceed on bad state and throws TypeError, RangeError and Error at its guard.

Points of care

  • node:buffer resolves inside Node.js without any package — it is a core module.

Putting it to use

Entry signature: export async function readStreamWithLimit(stream, maxBytes, options = {})

The surface worth importing is readStreamWithLimit; the helpers around it are private to the snippet.

Core lines

throw new TypeError("stream must be an async iterable readable stream");
throw new Error(`stream exceeded the ${maxBytes} byte limit`);
throw new RangeError("maxBytes must be a positive integer");

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
Validation comes first — `TypeError`, `RangeError` and `Error` marks the failure, before any partial work happens.
What does this import from outside the project?
Only `node:buffer`, and that is a Node.js built-in — it comes with the runtime.