O
O
overpod2014-12-15 09:15:43
Node.js
overpod, 2014-12-15 09:15:43

How to get value from such JAVASCRIPT node js code?

I'm not very good with JavaScript
here is the code

var request = require('request');

function getpage() {
  var xxxx;
    request('http://www.google.com', function(error, response, body) {
        if (!error && response.statusCode == 200) {
            //console.log(body) // Print the google web page.
            //здесь находится переменная body как её вернуть из функции getpage

        }
    });
    return xxxx; // как вернуть body
}

console.log(getpage());

The code is running on the nodejs server.
How to return page body from getpage function?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Prozorov, 2014-12-15
@Staltec

var request = require('request');

function getPageBody (url, callback) {
    request(url, function (error, response, body) {
        callback(error, body)
    });
}

getPageBody('http://www.google.com', function (err, body) {
    if (err) {
        console.log('ERROR:', err);
    } else {
        console.log('BODY:', body);
    }
});

A
Alexander Wolf, 2014-12-15
@mannaro

var req = require('request');
var Q = require('q');

function getPage(url) {
  var deferred = Q.defer();
  req(url, function(err, r, body) {
    if (error || r.statusCode != 200) {
      deferred.reject(new Error(err));
    } else {
      deferred.resolve(body);
    }
  });
  
  return deferred.promise;
}

getPage('http://google.com').then(function(body) {
  console.log(body);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question