Search code examples
javascriptnode.jshttphttprequestunirest

Retrieve data from request.end() in node.js


I want to use result of unirest request to another file in Node.js but I can not get data from request.end() function to outer variable.

Code is below:

request.end(function (response) {
        if(response.error) {
            console.log("AUTHENTICATION ERROR: ", response.error);
        } else {
            callback(null, response.body);
        }

        console.log("AUTHENTICATION BODY: ", response.body);
    });

var result = authentication(function(error, response) {
    var authenticationToken = response.access_token;

    if(authenticationToken != null) {
        console.log("Token: ", authenticationToken);

        return authenticationToken;
    }
});

I want to get authenticationToken value to export with module.exports for another modules.

I am using unirest http library.


Solution

  • its a callback function, and is treated as parameter, not a function that returns value.

    You can do this though:

    var result;
    authentication(function(error, response) {
        var authenticationToken = response.access_token;
    
        if(authenticationToken != null) {
            console.log("Token: ", authenticationToken);
    
            module.exports.result = authenticationToken; // setting value of result, instead of passing it back
        }
    });
    

    you can use result variable now. But be careful, its an asynchronous function, so you may not be able to use it immediately, until a value is assigned to it, within a callback function.

    To export result value:

    module.exports.result = null;
    

    Example

    m1.js

    setTimeout(() => {
       module.exports.result = 0;
    }, 0);
    
    module.exports.result = null;
    

    app.js

    const m1 = require('./m1.js');
    
    console.log(JSON.stringify(m1));
    
    setTimeout(() => {
      console.log(JSON.stringify(m1));
    
    }, 10);
    

    Output

    {"result":null}
    {"result":0}
    

    so you can keep using variable result, once the variable is assigned it would contain the value.