UNPKG

@naturalcycles/nodejs-lib

Version:
31 lines (30 loc) 873 B
import { Readable } from 'node:stream'; import { _passthroughMapper } from '@naturalcycles/js-lib/types'; /** * Create Readable from Array. * Supports a `mapper` function (async) that you can use to e.g create a timer-emitting-readable. * * For simple cases use Readable.from(...) (Node.js 12+) */ export function readableFromArray(items, mapper = _passthroughMapper, opt) { let i = -1; return new Readable({ objectMode: true, ...opt, async read() { i++; if (i < items.length) { try { this.push(await mapper(items[i], i)); } catch (err) { console.error(err); this.destroy(err); } } else { this.push(null); // end } }, }); }