Prerequisites: Node.js streams basics (write()/drain, pipeline()), async iterators, and objectMode transforms.
Implementation decision: keep the Transform narrow — it performs the per-chunk transform and manages an internal cancelled flag + cancel error. The async-iterator producer writes one item at a time to the Transform. After each write, check the boolean return; if false, await the Transform's 'drain' event before writing more. The cancel method is idempotent, stores the first error, and calls destroy(err) so pipeline() and connected streams fail together.
Expected result: the pipeline preserves input order, a fast producer cannot overload writable buffers, and cancel() immediately aborts the run with a visible error rather than letting the stream finish normally. Repeated cancellations do not overwrite the original reason.
One limitation: this pattern deliberately omits internal queuing or parallel processing inside the Transform. If you need parallelism, retries, or batching to hide slow consumers, treat those as separate components and add explicit testing for their interactions with backpressure and cancellation. Also perform integration tests against your actual sink (DB, network) because this minimal example focuses on the stream contract rather than raw resource limits.
Working example
import { Transform, Writable } from 'node:stream';
import { finished } from 'node:stream/promises';
function waitForDrain(stream) {
return new Promise((resolve, reject) => {
const cleanup = () => {
stream.off('drain', drained);
stream.off('error', failed);
stream.off('close', closed);
};
const drained = () => { cleanup(); resolve(); };
const failed = (err) => { cleanup(); reject(err); };
const closed = () => failed(stream.errored || Object.assign(new Error('Stream closed before drain'), {
code: 'ERR_STREAM_PREMATURE_CLOSE',
}));
stream.once('drain', drained);
stream.once('error', failed);
stream.once('close', closed);
if (stream.destroyed) closed();
});
}
export class CancellableTransform extends Transform {
constructor(opts = {}) {
super({ ...opts, objectMode: true });
this._cancelled = false;
this._cancelError = null;
}
cancel(err = new Error('Cancelled')) {
if (this._cancelled) return;
this._cancelled = true;
this._cancelError = err;
this.destroy(err);
}
async _transform(chunk, _enc, callback) {
try {
await Promise.resolve();
if (this._cancelled) throw this._cancelError;
this.push({ ...chunk, processed: true });
callback();
} catch (err) {
callback(err);
}
}
async runFromAsyncIterable(iterable) {
// Observe failure immediately, even while the producer is awaiting a value.
// Keep the result as a value until we can rethrow it to the caller.
const completion = finished(this, { readable: false, cleanup: true }).then(
() => null, (err) => err,
);
try {
if (this._cancelled) throw this._cancelError;
for await (const item of iterable) {
if (this._cancelled) throw this._cancelError;
if (this.destroyed) throw this.errored || new Error('Stream closed');
if (!this.write(item)) {
// A close without an error must also settle the wait for drain.
await waitForDrain(this);
}
}
this.end();
const error = await completion;
if (error) throw error;
} catch (err) {
if (!this.destroyed) this.destroy(err);
await completion;
throw err;
}
}
}
export function createCollector() {
const items = [];
const writable = new Writable({
objectMode: true,
write(chunk, _enc, callback) {
items.push(chunk);
callback();
},
});
// pipeline() is the single completion/error promise; no second, easily
// forgotten rejection is created by this collector.
return { writable, items };
}
Read the full article: https://chriseugenerodriguez.com/blog/cancellable-backpressure-transform-streams
Error ownership and cancellation boundary: Attach pipeline() and its rejection handler before calling cancel(), including when testing an already-cancelled transform. The collector exposes only its writable stream and items; pipeline() is the single completion/error promise. The feeder observes writable completion before ending input and handles close as well as error while waiting for drain. Cancellation cannot interrupt arbitrary work inside a producer that is awaiting its next value; that source must also accept a cooperative abort signal when prompt interruption of its I/O is required.