|
5 | 5 | Readable,
|
6 | 6 | } = require('stream');
|
7 | 7 | const assert = require('assert');
|
| 8 | +const { once } = require('events'); |
8 | 9 | const { setTimeout } = require('timers/promises');
|
9 | 10 |
|
10 | 11 | {
|
@@ -46,13 +47,80 @@ const { setTimeout } = require('timers/promises');
|
46 | 47 | })().then(common.mustCall());
|
47 | 48 | }
|
48 | 49 |
|
| 50 | +{ |
| 51 | + // Filter works on an infinite stream |
| 52 | + const stream = Readable.from(async function* () { |
| 53 | + while (true) yield 1; |
| 54 | + }()).filter(common.mustCall(async (x) => { |
| 55 | + return x < 3; |
| 56 | + }, 5)); |
| 57 | + (async () => { |
| 58 | + let i = 1; |
| 59 | + for await (const item of stream) { |
| 60 | + assert.strictEqual(item, 1); |
| 61 | + if (++i === 5) break; |
| 62 | + } |
| 63 | + })().then(common.mustCall()); |
| 64 | +} |
| 65 | + |
| 66 | +{ |
| 67 | + // Filter works on constructor created streams |
| 68 | + let i = 0; |
| 69 | + const stream = new Readable({ |
| 70 | + read() { |
| 71 | + if (i === 10) { |
| 72 | + this.push(null); |
| 73 | + return; |
| 74 | + } |
| 75 | + this.push(Uint8Array.from([i])); |
| 76 | + i++; |
| 77 | + }, |
| 78 | + highWaterMark: 0, |
| 79 | + }).filter(common.mustCall(async ([x]) => { |
| 80 | + return x !== 5; |
| 81 | + }, 10)); |
| 82 | + (async () => { |
| 83 | + const result = (await stream.toArray()).map((x) => x[0]); |
| 84 | + const expected = [...Array(10).keys()].filter((x) => x !== 5); |
| 85 | + assert.deepStrictEqual(result, expected); |
| 86 | + })().then(common.mustCall()); |
| 87 | +} |
| 88 | + |
| 89 | +{ |
| 90 | + // Throwing an error during `filter` (sync) |
| 91 | + const stream = Readable.from([1, 2, 3, 4, 5]).filter((x) => { |
| 92 | + if (x === 3) { |
| 93 | + throw new Error('boom'); |
| 94 | + } |
| 95 | + return true; |
| 96 | + }); |
| 97 | + assert.rejects( |
| 98 | + stream.map((x) => x + x).toArray(), |
| 99 | + /boom/, |
| 100 | + ).then(common.mustCall()); |
| 101 | +} |
| 102 | + |
| 103 | +{ |
| 104 | + // Throwing an error during `filter` (async) |
| 105 | + const stream = Readable.from([1, 2, 3, 4, 5]).filter(async (x) => { |
| 106 | + if (x === 3) { |
| 107 | + throw new Error('boom'); |
| 108 | + } |
| 109 | + return true; |
| 110 | + }); |
| 111 | + assert.rejects( |
| 112 | + stream.filter(() => true).toArray(), |
| 113 | + /boom/, |
| 114 | + ).then(common.mustCall()); |
| 115 | +} |
| 116 | + |
49 | 117 | {
|
50 | 118 | // Concurrency + AbortSignal
|
51 | 119 | const ac = new AbortController();
|
52 | 120 | let calls = 0;
|
53 | 121 | const stream = Readable.from([1, 2, 3, 4]).filter(async (_, { signal }) => {
|
54 | 122 | calls++;
|
55 |
| - await setTimeout(100, { signal }); |
| 123 | + await once(signal, 'abort'); |
56 | 124 | }, { signal: ac.signal, concurrency: 2 });
|
57 | 125 | // pump
|
58 | 126 | assert.rejects(async () => {
|
|
0 commit comments