Dan Savage Dan Savage - 3 months ago 6
Javascript Question

How to export a variable made by a request in node.js

In my first script, I execute a function which takes the HTML from a webpage. I'd like to use this HTML in another script, but the return always comes back as undefined...

var html;
exports.html = html;

exports.makeRequest = function makeRequest(url){
request({
url: url,
auth: {
user: '*****',
pass: '*****'
},
rejectUnauthorized: false,
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
html = body.toString();
exports.html = html;
}
});
}


I've tried making the variable a global, but to no avail.

This is the code I'm using to call the html.

var myRequests = require('./Request');

console.log(myRequests.makeRequest(url))

console.log(myRequests.html);

Answer

Sending a request is an async operation. That means you need to wait until the request is finished then retrieve the data via a callback.

exports.makeRequest = function makeRequest(url, cb) {
    request({
      url: url,
      auth: {
        user: '*****',
        pass: '*****'
      },
      rejectUnauthorized: false,
    }, function(error, response, body) {
      if (error) {
        return cb(er);
      }
      if (response.statusCode !== 200) {
        return cb(new Error('Request failed with code ' + response.statusCode));
      }
      cb(null, body.toString());
    });
  }
  //usage
var myRequests = require('./Request');

myRequests.makeRequest(url, function(er, html) {
  if (er) {
    return console.log(er);
  }
  console.log(html);
});
Comments