Skip to content

Instantly share code, notes, and snippets.

@rmg
Created May 22, 2016 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmg/891fd897ac357a8aa4dbee6df3d21230 to your computer and use it in GitHub Desktop.
Save rmg/891fd897ac357a8aa4dbee6df3d21230 to your computer and use it in GitHub Desktop.
Create a private buffer on an http response
const https = require('https');
const bufSym = Symbol();
https.get('https://nodejs.org/dist/index.json', onResponse);
function onResponse(res) {
// monkey patch using our Symbol as a key
res[bufSym] = '';
// event emitters invoke handlers using emitter as 'this'
res.on('data', accumulate);
res.on('end', doStuff);
}
// every response re-uses the same functions
function accumulate(data) {
this[bufSym] += data;
}
function doStuff() {
const body = this[bufSym];
// do our stuff here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment