Skip to content

Instantly share code, notes, and snippets.

@fxlemire
Last active June 17, 2019 15:03
Show Gist options
  • Save fxlemire/8c634e5beb9bc9e207b39d97f92e6c27 to your computer and use it in GitHub Desktop.
Save fxlemire/8c634e5beb9bc9e207b39d97f92e6c27 to your computer and use it in GitHub Desktop.
Node.js Playing With Streams (stream.pause)
// 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);
});
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