Last active
March 19, 2025 05:44
-
-
Save ardislu/b8b18018801da3a69d95ac0dbc3c64ab to your computer and use it in GitHub Desktop.
Demonstration of queuing strategy for Streams API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Demonstration of queuing strategy for Streams API | |
// $ node ./webStreamsQueuingStrategy.js | |
export { }; // Intentional unused export to force "type: module" on .js file | |
// These strategies are equivalent | |
const basicStrategy = { | |
highWaterMark: 3, // If no .size() specified, default is .size() === 1 (CountQueuingStrategy) | |
// size(chunk) { return 1; } // Implied | |
}; | |
const chunkStrategy = new CountQueuingStrategy({ | |
highWaterMark: 3 | |
}); | |
const elementsStrategy = { | |
highWaterMark: 3 * 4, // Assuming each chunk is a JSON array with exactly 4 elements | |
size(chunk) { return JSON.parse(chunk).length } | |
} | |
const strategies = [basicStrategy, chunkStrategy, elementsStrategy]; | |
const chunk = JSON.stringify(['a', 'b', 'c', 'd']); | |
for (const strategy of strategies) { | |
let i = 0; | |
const stream = new ReadableStream({ | |
pull(controller) { | |
if (i > 4) { | |
controller.close(); | |
} | |
else { | |
controller.enqueue(chunk); | |
console.log(`enqueued ${i}`); | |
i++; | |
} | |
} | |
}, strategy); | |
for await (const _ of stream) { | |
console.log('sink'); | |
} | |
console.log('---------------------------'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment