在将数据库记录到数组中的控制台之前检查URL是否存在

时间:2015-01-16 12:49:52

标签: arrays json node.js request

我正在编写用于生成站点地图的节点应用程序,并且遇到了我需要的特定部分的问题(i)在包含许多具有特定URL密钥的产品的JSON页面中循环,并检查URL是否存在对于每个产品和(ii)如果URL确实存在,则需要将此URL打印到控制台。

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
                {}
    })}

});

这样可以正常打印产品URL,此时它不会将[i]识别为数字并且给我一个错误。有没有其他方法可以将[i]的值传递给console.log,或者让它打印出与请求相同的链接?

2 个答案:

答案 0 :(得分:1)

尝试:

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
        processKey(body[i].urlKey);
    } 
});

function processKey(key) {
    request('http://www.example.com/product/' + key, 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/' + key +'"\n/>');
        }
        //if the product doesn't exist it does nothing
        else
        {
        }
    });
}

请参阅此问题以获取信息: JavaScript closure inside loops – simple practical example

答案 1 :(得分:0)

或者,如果您使用支持它的解释器,则可以在for语句中使用let关键字。

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 (let 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
                {}
    })}

});