UNPKG

909 BPlain TextView Raw
1import { Readable, ReadableOptions } from 'stream'
2import { _passthroughMapper, AbortableAsyncMapper } from '@naturalcycles/js-lib'
3import { ReadableTyped } from '../stream.model'
4
5/**
6 * Create Readable from Array.
7 * Supports a `mapper` function (async) that you can use to e.g create a timer-emitting-readable.
8 *
9 * For simple cases use Readable.from(...) (Node.js 12+)
10 */
11export function readableFromArray<IN, OUT>(
12 items: IN[],
13 mapper: AbortableAsyncMapper<IN, OUT> = _passthroughMapper,
14 opt?: ReadableOptions,
15): ReadableTyped<OUT> {
16 let i = -1
17
18 return new Readable({
19 objectMode: true,
20 ...opt,
21 async read() {
22 i++
23 if (i < items.length) {
24 try {
25 this.push(await mapper(items[i]!, i))
26 } catch (err) {
27 console.error(err)
28 this.destroy(err as Error)
29 }
30 } else {
31 this.push(null) // end
32 }
33 },
34 })
35}