ERR_STREAM_PREMATURE_CLOSE node streams ai_generated true

Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close

ID: node/node-stream-premature-close

Also available as: JSON · Markdown
87%Fix Rate
90%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
20 active

Root Cause

A stream was destroyed or closed before it finished being consumed. Common with HTTP responses, file streams, and pipeline operations.

generic

Workarounds

  1. 92% success Use stream.pipeline() instead of manual pipe chains for proper error propagation
    const { pipeline } = require('stream/promises'); await pipeline(readable, transform, writable);

    Sources: https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options

  2. 85% success Handle the 'error' and 'close' events on all streams in the pipeline
    readable.on('error', handleErr); writable.on('error', handleErr); writable.on('close', cleanup);

    Sources: https://nodejs.org/api/stream.html#event-close

Dead Ends

Common approaches that don't work:

  1. Ignoring the error by adding an empty error handler 80% fail

    The stream data is lost; downstream consumers receive incomplete data which causes silent data corruption

  2. Manually calling stream.destroy() then continuing to read 85% fail

    Once destroyed, a stream cannot be read from; any further read attempts throw or return null

Error Chain

Leads to:
Preceded by:
Frequently confused with: