我定義的必要app.js
,所有參數MySQL連接如何能在routes/
作出缺席可見的其他腳本,而不需要重新定義或MySQL的參數,只是用client.query(..)
?快車 - 傳遞MySQL連接到腳本
0
A
回答
3
你可以注入MySQL連接到其他的腳本是這樣的:
app.js
var mysqlConnection = new Conection(params);
require('controller/main.js)(mysqlConnection);
main.js
module.exports = function(mysqlConnection) {
// You can access your mysql connection here
};
UPDATE:
你可以注入幾個變量同樣的方式。
app.js
var mysqlConnection = new Conection(params);
var news = require('model/news.js)(app, mysqlConnection);
news.list(function(err, news) {
// Do something
});
news.js
module.exports = function(app, mysqlConnection) {
var methods = {};
// mysql connection and app available from here
methods.list = function(cb) {
mysqlConnection.list(function(err, data) {
cb(err, data);
});
};
return methods;
};
3
我用一個模式是建立我db
對象中:另外你是否需要這樣仍然可以導出從模塊的方法模塊一次並將其導出:(我們稱之爲utils/mySQL.js
)
//I haven't used real mysql in node so excuse the pseudo-syntax:
var db = require('mysql-driver-thingy');
db.connect('localhost', 'sqlport', options...);
db.otherSetupFunctions();
console.log("Finished db setup. You should only see this message once! Cool.");
module.exports = db;
然後我可以在任何我需要它的地方都可以使用db
對象。由於require
被緩存,所以這實際上不會多次調用設置方法。
在app.js:
var db = require('./utils/mySQL.js');
...
在模型/ user.js的:
var db = require('../utils/mySQL.js');
...
最後一個選擇,這是不推薦的,是污染全局命名空間。這似乎是你後真正的答案:
//set up your db
...
// and now make it available everywhere:
global.client = db.client
現在你可以神奇地使用客戶端對象中所有的模塊,甚至不需要它。
有很多原因全局是不好的,但:
- 如果你的代碼和其它代碼中定義全局變量,它們可能會出現衝突和相互覆蓋。
- 很難找到你所定義的
db
/client
對象等
的可能的複製[如何正確通過MySQL連接路線與express.js(http://stackoverflow.com/questions/16800418/how-to-properly-pass-mysql-connection-to-routes-with-express-js) – edjroot 2016-03-28 23:21:35
@EdJr什麼..你甚至看過問題之間的日期差異嗎? 2012年8月7日和2013年5月28日...你看到的區別對吧? – Gntem 2016-03-29 06:19:47
我舉報此問題的原因很充分。[This](https://meta.stackoverflow.com/a/315475/3089595)很好地總結了推理,並且它具有(有用的)鏈接來重複自身的事實是另一個很好的例子。 – edjroot 2016-03-29 06:46:20