Stream was closed before it finished
Production Risk
Can silently truncate file writes or HTTP responses if not handled in pipeline callbacks.
Thrown when a stream is destroyed or closed before it has finished processing. This error is emitted by the stream.finished() utility and by pipeline() when the underlying stream closes unexpectedly before the finish or end event fires.
- 1The underlying socket or file descriptor was closed mid-transfer
- 2stream.destroy() was called while data was still being written or read
- 3A piped source stream errored and destroyed the pipeline
Triggered by stream.finished() or stream.pipeline() when a stream closes before emitting finish/end.
const { pipeline, Readable, Writable } = require('stream');
const src = new Readable({ read() {} });
const dst = new Writable({ write(c, e, cb) { cb(); } });
pipeline(src, dst, (err) => {
console.error(err.code); // ERR_STREAM_PREMATURE_CLOSE
});
src.destroy(); // close source without pushing nullexpected output
Error [ERR_STREAM_PREMATURE_CLOSE]: Premature close
Fix 1
Always end streams properly before destroying
WHEN When you need to close a stream early
// Push null before destroying
src.push(null);
// Or pass an error to destroy to propagate it through the pipeline
src.destroy(new Error('Intentional close'));Why this works
Pushing null signals a clean EOF; passing an error to destroy() propagates the reason through the pipeline.
Fix 2
Handle ERR_STREAM_PREMATURE_CLOSE in pipeline callbacks
WHEN When streams can be closed by external events
pipeline(src, dst, (err) => {
if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
console.error('Unexpected pipeline error:', err);
}
});Why this works
Filtering the error code lets you distinguish expected early closures from real errors.
const { pipeline, Readable, Writable } = require('stream');
const src = new Readable({ read() {} });
const dst = new Writable({ write(c, e, cb) { cb(); } });
pipeline(src, dst, (err) => {
console.error(err.code); // ERR_STREAM_PREMATURE_CLOSE
}); // this triggers ERR_STREAM_PREMATURE_CLOSEtry {
// operation that may throw ERR_STREAM_PREMATURE_CLOSE
riskyOperation()
} catch (err) {
if (err.code === 'ERR_STREAM_PREMATURE_CLOSE') {
console.error('ERR_STREAM_PREMATURE_CLOSE:', err.message)
} else {
throw err
}
}const { pipeline } = require('stream/promises')
try {
await pipeline(src, dst)
} catch (err) {
if (err.code !== 'ERR_STREAM_PREMATURE_CLOSE') throw err
}✕ Destroy a stream without ending it when data transfer must complete
Premature destruction truncates data and fires this error through any attached pipeline.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev