Thursday, 25 May 2017

Return list of Objects with Node js

I recently started development of a Node js application and it uses Selenium in a controller to fetch list of items from a web page and I want to return the fetched list of items as a JSON response.

exports.read_all_products = function (req, res) {
    var driver = new webdriver.Builder().forBrowser('phantomjs').build();
    driver.get('https://www.test.com/products?PC=' +req.params.category);    
    driver.wait(until.elementLocated(By.className('product-slide-all')), 20000, 'Could not locate the element within the time specified');

    driver.findElements(By.className("product-slide-all")).then(function (elements) {
        var arr = [];
        elements.forEach(function (element) {
        element.getAttribute("innerHTML").then(function (html) {
            const dom = new JSDOM(html);
            var obj = new Object();
            obj.product_name = dom.window.document.querySelector(".product-name").textContent;
            obj.product_code = dom.window.document.querySelector(".product-code").textContent;
            obj.price = dom.window.document.querySelector(".product-price").textContent;
            arr.push(obj);
        });
    });
    res.json(arr);
    });
}

Issue is I am always getting an empty JSON response even though items were added to the array. I want to know the proper way of handling this scenario.

Thanks.



via Lakmal

No comments:

Post a Comment