我有一个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...");
但是当我启动网址时,无法看到任何回复。
我在这里遗漏了什么。
答案 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 );
});