Created
May 22, 2016 01:08
-
-
Save rmg/891fd897ac357a8aa4dbee6df3d21230 to your computer and use it in GitHub Desktop.
Create a private buffer on an http response
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 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