Last active
June 17, 2019 15:03
-
-
Save fxlemire/8c634e5beb9bc9e207b39d97f92e6c27 to your computer and use it in GitHub Desktop.
Node.js Playing With Streams (stream.pause)
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
// This is a quick gist to validate that data transmitted when a response stream is paused is not lost | |
const request = require('request'); | |
const stream = request.get('http://127.0.0.1:3000/'); | |
console.log('fetching...'); | |
stream.on('response', response => { | |
console.log('got response'); | |
response.pause(); | |
response.on('end', () => { | |
console.log('end'); | |
}); | |
setTimeout(() => { | |
console.log('reading stream'); | |
/* | |
* Uncomment the resume call and the 'end' event will be triggered and the stream will be read as chunks | |
* Leave it commented and the chunk willbe read as a whole sentence | |
*/ | |
// response.resume(); | |
let chunk; | |
while (null !== (chunk = response.read())) { | |
console.log(`Received ${chunk}`); | |
} | |
}, 10000); | |
}); |
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
const express = require('express'); | |
const app = express(); | |
const port = 3000; | |
app.get('/', (req, res) => { | |
const str = 'hello'; | |
const write = (count = 0) => { | |
if (count >= str.length) { | |
console.log('ending stream'); | |
res.end(); | |
} else { | |
console.log(`writing ${str.charAt(count)}`); | |
res.write(str.charAt(count)); | |
setTimeout(() => write(count + 1), 500); | |
} | |
}; | |
write(); | |
}); | |
app.listen(port, () => console.log(`Example app listening on port ${port}!`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment