Return values from module.exports by return

1

I have the following code that the data is returning right by console.log()

var request = require("request");
var myJSON = require("JSON");

function resultado(url, callback) {
    request({
        url: url,
        json: true
    }, function(error, response, body) {
        callback(null, body);
    });
}


module.exports.cfg = resultado('http://localhost/conf/site', function(err, body) {
    console.log(body)
    return body
});

When I do not require this file in another

var conf = require('./config/config')
console.log(conf.cfg);

It returns undefined

Anyone there could help me how to recover these values is can they use them? equal returns no console.log(body) ?

or is there any package that already does this?

    
asked by anonymous 01.06.2017 / 18:41

1 answer

0

module.exports is not an object by itself. If you make module.exports = 'foo'; it will export a string. That is, you have to explicitly = {}; .

But there is another problem, is that this function is asynchronous, so it is best to export the function. My suggestion is:

module.exports = resultado;

and then use this:

var conf = require('./config/config');
cfg('http://localhost/conf/site', (err, body){
    if (err) console.log(err);
    console.log(body);
    // e aqui dentro podes continuar o código com o body disponível
});
    
01.06.2017 / 18:57