Search code examples
node.jsrequire

how can return value with require file in node js?


I am new to node.js , and use ari client. I have two .js files that first one is required in second one. I have declared a variable in second one that must contain return value of first file but console.log(variable) is undefined although in first file return value is not null.

in first file :

var db = require("./database.js");
var service_info = db.select(connection,'select * from services where ivr_shortcode = ?',service);
console.log(service_info);

service_info is undefined;

in second file :

this.select = function (connection,query,data){
connection.query(query,[data],function(err, results){
    if(err)
    {
        throw err;
    }
    else
    {
        return results;
    }
});}

Solution

  • You cannot just return values from callback due to call being asynchronous, you should use another function to get the results:

    // file 'database.js'
    exports.select = function (connection, query, data, callback) {
        connection.query(query, [data], callback);
    }
    

    Than in your main:

    // I assume `connection` and `service` are defined somewhere before (like in your original code)
    var db = require("./database.js");
    var service_info = db.select(connection,'select * from services where ivr_shortcode = ?',service, function(err, service_info){
      console.log(service_info);
    });
    

    P.S. You should really read some docs and look into Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference to get better understanding of scope visibility and closures