UNPKG

@naturalcycles/nodejs-lib

Version:
33 lines (32 loc) 979 B
import { Transform } from 'node:stream'; import { PIPELINE_GRACEFUL_ABORT } from '../stream.util.js'; import { transformNoOp } from './transformNoOp.js'; export function transformLimit(opt) { const { limit, signal, objectMode = true, highWaterMark = 1 } = opt; if (!limit) { return transformNoOp(); } let i = 0; // so we start first chunk with 1 let ended = false; return new Transform({ objectMode, highWaterMark, transform(chunk, _, cb) { if (ended) { return; } i++; if (i === limit) { ended = true; this.push(chunk); this.push(null); // tell downstream that we're done cb(); queueMicrotask(() => { signal.abort(new Error(PIPELINE_GRACEFUL_ABORT)); }); return; } cb(null, chunk); }, }); }