如何在各个 NodeJS 模块之间共享数据库连接?我发现的示例都具有整体结构,其中整个代码都在一个 app.js 文件中。
/* main.js */
var foo = require("./foo");
/* express stuff ...*/
mysql = /* establish mysql connection */
app.get("/foo", foo.hello );
/* foo.js */
exports.hello = function(req, res) {
res.send("Hello from the foo module!");
}
我如何从我的模块“foo”访问“mysql”?为此推荐的设计模式是什么?
最佳答案
您可以使用模块模式轻松地将数据库对象(以及其他任何内容)传递给需要它的模块。
// users.js
module.exports = function( options ) {
var db = options.db;
var pants = options.pants; // or whatever
return {
GetUser: function( userID, callback ) {
db.query("....", function (err, results) {
callback(results)
});
},
AnotherFunc: function (...) {},
AndAnotherFunc: function (...) {}
};
};
您可以像这样使用此模块:
// make your db connection here
var users = require('./users.js')({
db: db,
pants: 'blue'
});
users.GetUser( 32, function( user ) {
console.log("I got the user!");
console.log( user );
});
我发现这是编写模块的好方法,因为它很像创建一个实际的 Class 对象,就像在 C++ 中一样。您甚至可以模拟“私有(private)”方法/参数。
关于database - Node.JS 中共享数据库句柄的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20935372/