无法从模块导出中获取变量

时间:2016-06-29 17:47:39

标签: node.js express massivejs

我有一个connector.js文件,我想用它来导出dbResult对象。

(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);

现在在另一个文件中我试图获取dbResult并显示数据:

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...");

但是当我启动网址时,无法看到任何回复。

我在这里遗漏了什么。

1 个答案:

答案 0 :(得分:1)

您想要做的是返回一个函数,以后可以对结果进行评估:

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

然后您可以从其他文件中访问它:

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