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
});
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1c0afa7-32a40.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1c0afa7-32a40.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?