Created
December 10, 2014 16:44
-
-
Save isner/86988d1c395b9d8ea537 to your computer and use it in GitHub Desktop.
Parallel url-scanner with concurrency limit
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
var http = require('http'); | |
function async(url, next) { | |
// Log for demo purposes - remove | |
console.log('url: ', url); | |
http.get(url, function (res) { | |
// setTimeout for demo purposes - remove | |
setTimeout(function () { | |
next(res.statusCode); | |
}, 1000); | |
}); | |
} | |
function done() { | |
console.log('Done', results); | |
process.exit(0); | |
} | |
var urls = [ | |
'http://google.com', | |
'http://yahoo.com', | |
'http://google.com', | |
'http://yahoo.com', | |
'http://google.com', | |
'http://yahoo.com', | |
'http://google.com', | |
'http://yahoo.com', | |
]; | |
var results = []; | |
var running = 0; | |
// Set your concurrency limit here | |
var limit = 2; | |
function start() { | |
while(running < limit && urls.length > 0) { | |
var url = urls.shift(); | |
async(url, function(result) { | |
results.push(result); | |
running--; | |
if(urls.length > 0) { | |
start(); | |
} else if (running === 0) { | |
done(); | |
} | |
}); | |
running++; | |
} | |
} | |
start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment