Express-将mysql连接传递给脚本 [英] Express - Passing mysql connection to scripts
本文介绍了Express-将mysql连接传递给脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用 app.js
必需的所有参数定义了mysql连接,如何使 routes/
中的其他脚本可见默认情况下,无需使用或重新定义mysql参数,只需使用 client.query(..)
?
I defined mysql connection with all parameters necessary to app.js
, how can make visible to other scripts in routes/
by default, without requiring or redefining mysql parameters, just using client.query(..)
?
推荐答案
您可以将mysql连接注入到其他脚本中,如下所示:
You can inject mysql connection into other scripts like this:
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
};
更新:
您可以以相同的方式注入多个变量.如果需要,您仍然可以从模块中导出方法:
You can inject several variables same way. Also you still can export methods from module if you need this:
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;
};
这篇关于Express-将mysql连接传递给脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文