Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Last active August 28, 2016 20:21
Show Gist options
  • Save dengjonathan/871d0981ff985261e5ef0768a247c767 to your computer and use it in GitHub Desktop.
Save dengjonathan/871d0981ff985261e5ef0768a247c767 to your computer and use it in GitHub Desktop.
Node asyn I/O with callback after I/O returns
var http = require('http');
var bl = require('bl');
// file path is from enviroment variable passed in through CLI
var url = process.argv[2];
var consolidated = '';
var callback = function(data) {
consolidated += data;
};
// http get request takes a callback with signature callback(response)
http.get(url, function(response) {
// set encoding to UTF to print string rather than buffer object
//response.setEncoding('utf8');
// error callback
response.on('error', function(err) {
console.error("Error: ${err}");
});
// data call back
// Response is a stream object, which will continuously emit events
// you can trigger specific call backs on specific events from Response
response.pipe(bl(function(err, data) {
if (err) {
console.err(err);
}
data = data.toString();
console.log(data.length);
console.log(data);
}));
}).on('error', function(err) {
console.error("There was an error submitting the http request.");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment