Skip to content

Instantly share code, notes, and snippets.

@cdax
Last active August 29, 2015 14:10
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 cdax/5bcc7e4e7347f44a526f to your computer and use it in GitHub Desktop.
Save cdax/5bcc7e4e7347f44a526f to your computer and use it in GitHub Desktop.
A callback-style asynchronous function in Node
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