UNPKG

775 BPlain TextView Raw
1import { Transform } from 'stream'
2import { TransformOptions, TransformTyped } from '../stream.model'
3
4/**
5 * 0 or falsy value means "no limit"
6 */
7export function transformLimit<IN>(
8 limit?: number,
9 opt: TransformOptions = {},
10): TransformTyped<IN, IN> {
11 let index = 0
12 let ended = false
13
14 return new Transform({
15 objectMode: true,
16 ...opt,
17 transform(this: Transform, chunk: IN, _encoding, cb) {
18 index++
19
20 if (!ended) {
21 cb(null, chunk) // pass through the item
22 } else {
23 cb(null) // pass-through empty
24 }
25
26 if (limit && index === limit) {
27 ended = true
28 console.log(`transformLimit: limit of ${limit} reached`)
29 // this.emit('end') // this makes it "halt" on Node 14 lts
30 }
31 },
32 })
33}