Stream unshift() called after end event
Production Risk
Low — typically only affects custom stream parsers.
Thrown when readable.unshift() is called after the end event has been emitted. unshift() pushes data back to the front of the read queue; once end has fired the stream is finished and no more data can be enqueued.
- 1Calling unshift() in an end event handler
- 2Async code that calls unshift() after the stream has already ended
- 3Protocol parser that tries to put back data after it detects stream end
Triggered when unshift() is called on a Readable that has already emitted its end event.
const { Readable } = require('stream');
const r = Readable.from(['a', 'b']);
r.on('end', () => {
r.unshift('c'); // throws — stream already ended
});
r.resume();expected output
Error [ERR_STREAM_UNSHIFT_AFTER_END_EVENT]: stream.unshift() after end event
Fix
Check readable.readableEnded before calling unshift()
WHEN In parsers or protocol handlers that may put back data
if (!readable.readableEnded) {
readable.unshift(leftover);
}Why this works
The readableEnded flag indicates whether end has been emitted; guarding on it prevents the error.
const { Readable } = require('stream');
const r = Readable.from(['a', 'b']);
r.on('end', () => {
r.unshift('c'); // throws — stream already ended
});
r.resume(); // this triggers ERR_STREAM_UNSHIFT_AFTER_END_EVENTtry {
// operation that may throw ERR_STREAM_UNSHIFT_AFTER_END_EVENT
riskyOperation()
} catch (err) {
if (err.code === 'ERR_STREAM_UNSHIFT_AFTER_END_EVENT') {
console.error('ERR_STREAM_UNSHIFT_AFTER_END_EVENT:', err.message)
} else {
throw err
}
}// Validate inputs before calling the operation
function safe_err_stream_unshift_after_end_event(...args) {
// validate args here
return performOperation(...args)
}✕ Call unshift() inside end event handlers
The stream is already finished at end; unshift() cannot add data to a closed stream.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev