2

I am very new in Node.js and javasript. Is it possible return value from request? Thanks

 var request = require('request');
//parse text
 function(text) {
 request(text, function (error, response, body) {
  if (!error && response.statusCode == 200) {

    var $ = cheerio.load(body);
    //get title
    var title = $("title").text();

})

I NEED TITLE HERE

};
EK.
  • 2,890
  • 9
  • 36
  • 49
  • It is a callback function and its asynchronous in nature. Because at that time of request its not possible to know about when it is going to receive a response. Better assign title to a global variable. – Tintu C Raju Apr 13 '15 at 07:54

1 Answers1

0

to do that you need to understand the async nature of node, at that moment title might not be available, since the request to get the title is async, so you have to wait for response to come back before you can access it

you can do like this

   function getTitle(uri, callback) {
      request(uri, function (error, response, body) {
        if (error || response.statusCode != 200) {
           return callback(error);
        }
        var $ = cheerio.load(body);
        //get title
        return callback(null, $("title").text());
      });
   }

   getTitle(uri, function(err, title) {
     //access title here
   });
Edgar Zakaryan
  • 576
  • 5
  • 11