The Goal:
Given an array of URLs, I need to send a request and get back the statusCode for each one. Finally, I need to match that statusCode with the request URL in an array of objects which can then be returned to the page.
Like this:
checkList: [
{
name: "Google",
url: "https://www.google.com"
},
{
name: "Microsoft",
url: "https://www.microsoft.com"
},
{
name: "Github",
url: "https://www.github.com"
}
]
For each URL in the list, I need to simply make an http request and get back a status code (eg: 200) and match that with the request path. So the final output should look like this...
results: [
{
name: "Google",
url: "https://www.google.com",
status: 200
},
{
name: "Microsoft",
url: "https://www.microsoft.com",
status: 200
},
{
name: "Github",
url: "https://www.github.com",
status: 200
}
]
I'm currently using BluebirdJS and Needle to handle the async calls to get the response codes.
The problem is that I can't see a way to match the requesting URL with the response. Since each result comes back at different times (as intended) and the Needle response doesn't include the request URL, I can't say something like... "https://google.com response is 200". I can only get a list of response codes.
I'm relatively new to advanced JS, so maybe there's a way to override callbacks/promises which allow me to pass the request URL through the entire process, but I don't know how.
This is a Gist of the code I'm currently using based on demos/snippets I've found elsewhere... https://gist.github.com/sgelliott/13840b6f2f9d2ab481fcded6dc4a9188
The code also included inline below...
var needle = require('needle');
var Promise = require("bluebird");
Promise.promisifyAll(needle);
var allPaths = ["https://google.com", "https://microsoft.com", "https://github.com"];
var current = Promise.resolve();
Promise.map(allPaths, function(path) {
current = current.then(function() {
console.log("path: " + path); // path shows up here correctly - it's available
return needle.getAsync(path, options);
});
return current;
}).map(function(resp, body) {
return {
path: "path goes here",
status: resp.statusCode
};
}).then(function(results) {
console.log("results: " + JSON.stringify(results)); // this outputs 'resulst' : [{"path":"path goes here","status":200},{"path":"path goes here","status":302},{"path":"path goes here","status":200}]
return renderResults(results); //this simply sets 'statusResults' to 'results' for the next res.send to use - will refine once I solve the path matching issue
}).then(function() {
console.log('All Needle requests are processed!');
res.send(statusResults); //
}).catch(function(e) {
console.log(e);
});
I apologize if this is a duplicate of something else. I wasn't able to find it after a lot of research. If the solution is to use something other than Needle, that's perfectly fine. I'd prefer to stick with Bluebird though. Thank you in advance!