Streaming Response With Backpressure

Stream large responses with backpressure and content-type headers for memory-efficient file serving.

TypescriptFile Upload

Code

typescriptsnippet
1 line
import{Readable}from'node:stream';export function streamingResponse(source:Readable,{contentType='application/octet-stream',contentLength}:{contentType?:string;contentLength?:number}={}){const headers:Record<string,string>={'content-type':contentType,'cache-control':'no-cache'};if(contentLength)headers['content-length']=String(contentLength);return{headers,body:source};}export function jsonStream(items:AsyncIterable<unknown>){const readable=Readable.from((async function*(){yield'[';let first=true;for await(const item of items){if(!first)yield',';yield JSON.stringify(item);first=false;}yield']';})());return streamingResponse(readable,{contentType:'application/json'});}

Inside the snippet

Streaming Response With Backpressure keeps everything in the functions streamingResponse and jsonStream.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import names the platform contact area: Readable, all from node:stream.

The result comes back as an object carrying headers.

Watch out for

  • The dependency surface is just node:stream, and that one is built into Node.js.

Putting it to use

Signature: export function streamingResponse(source:Readable,{contentType='application/octet-stream',contentLength}:{c…

streamingResponse is the public entry point; everything else in the file exists to support it.

The call returns headers.

FAQ

Do I need to install anything before running this?
Nothing needs installing: `node:stream` ships with Node.js itself.
What does `streamingResponse` return?
An object carrying `headers`.