Can nodejs return request module data as a global variable

can nodejs return request module data as a global change

related codes

var request = require("request");
var URL = require("url");
var iconv = require("iconv-lite");

var url = "https://segmentfault.com/q/1010000010487842/";

request({
    encoding: null,
    url: url
}, function (error, response, body) {

    
    var array1 = /<title>(.*)<\/title>/gi.exec(body);
    if (array1 != null) {
          var title = array1[1];
        //console.log(title);
    }
  
    console.log(title);
    return title;//
    
});
//console.log(title);//titletitle is not defined

//

whether title can be returned as a global variable.

Apr.01,2021

it seems that you don't know much about what asynchrony is, so it is recommended to look for the basic article on asynchrony first.
in your case, you can wrap it in promise and return a promise to the outside. You can also provide the acquired title by callback function.
it's not clear if you understand promise, so it's implemented with a simple callback function for the time being.

var title;
module.exports.getTitle = function(callback) { 
  if(title) {
    return callback(null, title);
  }

  request({
    encoding: null,
    url: url
  }, function (error, response, body) {
    if(error) {
      return callback(error);
    }
    var array1 = /<title>(.*)<\/title>/gi.exec(body);
    if (array1 != null) {
      title = array1[1];
    }
    return callback(null, title);
  });
}
When calling

externally, use it this way, assuming that the above package name is titleModule

var titleModule = require('./titleModule');

titleModule.getTitle(function(err, title) {
    console.log(title); //title
});
Menu