Created
June 9, 2019 08:13
-
-
Save artze/64da6d6f44ad449323751c19766fd142 to your computer and use it in GitHub Desktop.
Basic writable stream backpressure example
This file contains 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
const Chance = require('chance'); | |
const http = require('http'); | |
const chance = new Chance(); | |
http.createServer((req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/plain' }); | |
const generateMore = () => { | |
while(chance.bool({ likelihood: 95 })) { | |
let shouldContinue = res.write( | |
chance.string({ length: (16 * 1024) - 1 }) | |
); | |
if(!shouldContinue) { // [1] | |
console.log('backpressure'); | |
return res.once('drain', generateMore); | |
} | |
} | |
res.end('\n The end... \n', () => { // [2] | |
console.log('All data was sent') | |
}) | |
} | |
generateMore(); | |
}) | |
.listen(3000, () => { | |
console.log('Listening on port 3000'); | |
}) | |
// [1] Triggers when internal buffer is full. Return statement stops out | |
// of function and registers a one-time 'drain' listener, which | |
// waits for buffer to be flushed before invoking generateMore() | |
// | |
// [2] Signal end of write stream when while condition fails |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment