mardi 14 juin 2016

Node.js return html as a variable

I'm setting up a web scraper using Node.js and want to grab some html from a url and save it as a variable. A stripped down version follows.

var request = require('request');
var get_html = function(){
    var url = "http://www.google.com";
    var html = '';
    request.get(url,function(error, response, body){
        html += body;
    });
    return html;
};
console.log(get_html());

It seems that the function returns before request can concatenate the html to the variable html. As far as I can see, request only allows me to manipulate the html within the callback function or pipe it to a file. Is there anyway to just return it as a variable?

Aucun commentaire:

Enregistrer un commentaire