I would like to return some of the body from a request made in request.js to the module that calls it in app.js
I have tried using module.exports to save information in the body. I know that the request is asynchronous so I have to wait for it to come back but I am not sure how to do this.
My app.js file:
const yargs = require('yargs');
const fs = require('fs');
const argv = yargs.
options({
capcity: {
description: 'capital city',
alias: 'c',
demand: true
}
})
.help()
.argv;
module.exports.capcity = argv.capcity;
const requestData = require('./requestData.js');
console.log(requestData.country);
My requestData.js file:
const request = require('request');
const app = require('./app.js');
var country;
request({
url: `https://restcountries.eu/rest/v2/capital/${app.capcity}`,
json: true
}
, (error, response, body) => {
console.log(app.capcity);
if (error) {
console.log('error:', error);
} else if (body.status == 404) {
console.log(JSON.stringify(body, undefined, 2));
console.log("invalid city entered");
} else {
country = {
name: body[0].name,
code: body[0].currencies[0].code,
symbol: body[0].currencies[0].symbol
}
country = JSON.stringify(country);
console.log(country);
}
});
module.exports.country = country;
It returns that country is undefined.