简体   繁体   中英

Unable to get variable from module exports

I have a connector.js file which using which I want to export dbResult object.

(function(){
var Massive = require("massive");

var connectionString = "postgres://postgres:postgres@localhost/postgres";
var db = Massive.connectSync({connectionString : connectionString});

var dbResult ;

 db.query("Select * from company", function (err, data) {
        dbResult = data;
        console.log(data);
    });
})(module.exports);

Now in Another file I am trying to get the dbResult and display the data:

var express = require("express");
var app = express();

var connectorObject = require("./Connector.js");

var Massive = require("massive");

app.get("/api/Steves",function(req,res){

        res.set("Content-Type","application/json");
        res.send(connectorObject.dbResult);
    });


app.listen(3000);

console.log("Server Started on port 3000...");

But when I start the URL , not able to see any response .

Am I missing anything here.

What you want to do, is return a function that can be evaluated later for the result:

var Massive = require("massive");

var connectionString = "postgres://postgres:postgres@localhost/postgres";
var db = Massive.connectSync({connectionString : connectionString});

module.exports.getCompanies = function(callback) {
    db.query("Select * from company", callback);
}

Then you can access it from your other files as:

var connector = require('./Connector');
connector.getCompanies(function( err, data ) {
    if ( err ) return console.error( err );
    console.log( data );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM