ERR_STREAM_UNSHIFT_AFTER_END_EVENT
Node.jsERRORNotableStreamHIGH confidence

Stream unshift() called after end event

Production Risk

Low — typically only affects custom stream parsers.

What this means

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.

Why it happens
  1. 1Calling unshift() in an end event handler
  2. 2Async code that calls unshift() after the stream has already ended
  3. 3Protocol parser that tries to put back data after it detects stream end
How to reproduce

Triggered when unshift() is called on a Readable that has already emitted its end event.

trigger — this will error
trigger — this will error
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

Check readable.readableEnded before calling unshift()
if (!readable.readableEnded) {
  readable.unshift(leftover);
}

Why this works

The readableEnded flag indicates whether end has been emitted; guarding on it prevents the error.

Code examples
Triggerjs
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_EVENT
Handle in try/catchjs
try {
  // 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
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_stream_unshift_after_end_event(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Call unshift() inside end event handlers

The stream is already finished at end; unshift() cannot add data to a closed stream.

Same error in other languages
Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors