1'use strict'; 2 3const common = require('../common'); 4const { 5 Readable, 6} = require('stream'); 7const assert = require('assert'); 8 9{ 10 // Works on a synchronous stream 11 (async () => { 12 const tests = [ 13 [], 14 [1], 15 [1, 2, 3], 16 Array(100).fill().map((_, i) => i), 17 ]; 18 for (const test of tests) { 19 const stream = Readable.from(test); 20 const result = await stream.toArray(); 21 assert.deepStrictEqual(result, test); 22 } 23 })().then(common.mustCall()); 24} 25 26{ 27 // Works on a non-object-mode stream 28 (async () => { 29 const firstBuffer = Buffer.from([1, 2, 3]); 30 const secondBuffer = Buffer.from([4, 5, 6]); 31 const stream = Readable.from( 32 [firstBuffer, secondBuffer], 33 { objectMode: false }); 34 const result = await stream.toArray(); 35 assert.strictEqual(Array.isArray(result), true); 36 assert.deepStrictEqual(result, [firstBuffer, secondBuffer]); 37 })().then(common.mustCall()); 38} 39 40{ 41 // Works on an asynchronous stream 42 (async () => { 43 const tests = [ 44 [], 45 [1], 46 [1, 2, 3], 47 Array(100).fill().map((_, i) => i), 48 ]; 49 for (const test of tests) { 50 const stream = Readable.from(test).map((x) => Promise.resolve(x)); 51 const result = await stream.toArray(); 52 assert.deepStrictEqual(result, test); 53 } 54 })().then(common.mustCall()); 55} 56 57{ 58 // Support for AbortSignal 59 const ac = new AbortController(); 60 let stream; 61 assert.rejects(async () => { 62 stream = Readable.from([1, 2, 3]).map(async (x) => { 63 if (x === 3) { 64 await new Promise(() => {}); // Explicitly do not pass signal here 65 } 66 return Promise.resolve(x); 67 }); 68 await stream.toArray({ signal: ac.signal }); 69 }, { 70 name: 'AbortError', 71 }).then(common.mustCall(() => { 72 // Only stops toArray, does not destroy the stream 73 assert(stream.destroyed, false); 74 })); 75 ac.abort(); 76} 77{ 78 // Test result is a Promise 79 const result = Readable.from([1, 2, 3, 4, 5]).toArray(); 80 assert.strictEqual(result instanceof Promise, true); 81} 82{ 83 // Error cases 84 assert.rejects(async () => { 85 await Readable.from([1]).toArray(1); 86 }, /ERR_INVALID_ARG_TYPE/).then(common.mustCall()); 87 88 assert.rejects(async () => { 89 await Readable.from([1]).toArray({ 90 signal: true 91 }); 92 }, /ERR_INVALID_ARG_TYPE/).then(common.mustCall()); 93} 94