Last active
August 28, 2016 20:21
-
-
Save dengjonathan/871d0981ff985261e5ef0768a247c767 to your computer and use it in GitHub Desktop.
Node asyn I/O with callback after I/O returns
This file contains 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
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