Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js http.get as a function

Node.js http.get as a function

Problem

I am trying to make a function that returns the content of the webpage and this is what I have so far

var get_contents = function() {
    var httpRequestParams = 
    {
        host: "google.com",
        port: 80,
        path: "/?"
    };

    var req = http.get(httpRequestParams, function(res) 
    {
        var data = '';
        res.on('data', function(chunk) {
            data += chunk.toString();
        });
        //console.log(data);
    }).end();

    return req;
}

This when I run this code, I see the html contents when the console logging is turned on but when I try to return the output, it just never works.

I can't figure out a way to return get_contents() anywhere. On the console, it just doesnt respond.

Thanks

Problem courtesy of: Kartik

Solution

Something like that: (dont forget to handle error and timeout)

var on_contents = function(cb) {
    var httpRequestParams = 
    {
        host: "google.com",
        port: 80,
        path: "/?"
    };

    var req = http.get(httpRequestParams, function(res) 
    {
        var data = '';
        res.on('data', function(chunk) {
            data += chunk.toString();
        });

        res.on('end', function(){
            cb(data);
        });

        //console.log(data);
    }).end();

}

function onFinish(data) {
    console.log(data);

}

on_contents(onFinish)
Solution courtesy of: Vodun

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js http.get as a function

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×