Last active
August 29, 2015 14:10
-
-
Save cdax/5bcc7e4e7347f44a526f to your computer and use it in GitHub Desktop.
A callback-style asynchronous function in Node
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 download = function(url, callback) { | |
var page = ''; | |
http.get(url, function(res) { | |
res.on('data', function(chunk) { | |
page += chunk.toString(); | |
}); | |
res.on('end', function() { | |
//Successful callback | |
callback(null, page); | |
}); | |
res.on('error', function(err) { | |
//Error callback | |
callback(err, null); | |
}); | |
}); | |
}; | |
//Calling download | |
downlaod('http://nodejs.org', function(err, page) { | |
if(err) | |
console.log(err); | |
else | |
console.log('Downloaded.'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment