Return module.Exports values by Return

Asked

Viewed 547 times

2

I have the following code that the data are 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 require in that file in another

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

he returns Undefined

someone ai could help me how to recover these values is can use them ? equals returns in console.log(body) ?

or if there is any package that already does that ?

1 answer

1

module.exports is not an object in itself. If you do module.exports = 'foo'; it will export a string. In other words, you must explicitly = {};.

However 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 like 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
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.