MCPcopy Create free account
hub / github.com/nodejs/node / toReadable

Function toReadable

lib/internal/streams/iter/classic.js:263–339  ·  view source on GitHub ↗

* Create a byte-mode Readable from an AsyncIterable . * The source must yield Uint8Array[] batches (the stream/iter native * format). Each Uint8Array in a batch is pushed as a separate chunk. * @param {AsyncIterable } source * @param {object} [options] * @param {number

(source, options = kNullPrototype)

Source from the content-addressed store, hash-verified

261 * @returns {stream.Readable}
262 */
263function toReadable(source, options = kNullPrototype) {
264 if (typeof source?.[SymbolAsyncIterator] !== 'function') {
265 throw new ERR_INVALID_ARG_TYPE('source', 'AsyncIterable', source);
266 }
267
268 validateObject(options, 'options');
269 const {
270 highWaterMark = 64 * 1024,
271 signal,
272 } = options;
273 validateInteger(highWaterMark, 'options.highWaterMark', 0);
274
275 const ReadableCtor = lazyReadable();
276 const iterator = source[SymbolAsyncIterator]();
277 let backpressure;
278 let pumping = false;
279 let done = false;
280
281 const readable = new ReadableCtor({
282 __proto__: null,
283 highWaterMark,
284 read() {
285 if (backpressure) {
286 const { resolve } = backpressure;
287 backpressure = null;
288 resolve();
289 } else if (!pumping && !done) {
290 pumping = true;
291 pump();
292 }
293 },
294 destroy(err, cb) {
295 done = true;
296 // Wake up the pump if it's waiting on backpressure so it
297 // can see done === true and exit cleanly.
298 if (backpressure) {
299 backpressure.resolve();
300 backpressure = null;
301 }
302 if (typeof iterator.return === 'function') {
303 PromisePrototypeThen(iterator.return(),
304 () => cb(err), (e) => cb(e || err));
305 } else {
306 cb(err);
307 }
308 },
309 });
310
311 if (signal) {
312 addAbortSignalNoValidate(signal, readable);
313 }
314
315 async function pump() {
316 try {
317 while (!done) {
318 const { value: batch, done: iterDone } = await iterator.next();
319 if (iterDone) {
320 done = true;

Callers 15

testBasicAsyncFunction · 0.85
testMultiBatchAsyncFunction · 0.85
testBackpressureAsyncFunction · 0.85
testErrorAsyncFunction · 0.85
testEmptyAsyncFunction · 0.85
testEmptyBatchAsyncFunction · 0.85
testDestroyAsyncFunction · 0.85
testLargeDataAsyncFunction · 0.85
testPipeAsyncFunction · 0.85
testNotObjectModeFunction · 0.85
testInvalidSourceAsyncFunction · 0.85

Calls 1

lazyReadableFunction · 0.85

Tested by

no test coverage detected