I'm writing a node app for generating sitemaps and am having trouble with a particular part that I need to (i) Loop through a JSON page containing a number of products with specific URL keys and check if the URL exists for each of these products and (ii) if the URL does exist it needs to print this URL to the console.
var request = require("request");
var url = "http://linktoJSON"
//reads the JSON from the provided URL
request({
url: url,
json: true
}, function (error, response, body) {
//loops through each product on the page
for (i = 0; i < body.length; i++) {
//checks if the URL exists for each product
request('http://www.example.com/product/' + (body[i].urlKey), function (err, response) {
//if the product page does exist
if (response.statusCode === 200) {
//print the product URL
console.log (('<xtml:link\nrel="alternate"\nhreflang="x-default"\nhref="http://www.example.com/' + body[i].urlKey) +'"\n/>');
}
//if the product doesn't exist it does nothing
else
{}
})}
});
This works fine up to the point where it should print the product URL, at this point it is not recognising [i] as a number and is giving me an error. Is there any other way to pass the value of [i] to the console.log or get it to print the exact same link as it is using for the request?