NodeJS/Express - 在路由器文件中提供可用的MySQL连接对象

Llo*_*nks 5 node.js express node-mysql

我的app.js文件中有以下内容:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'user',
    password: 'password',
    database: 'mydatabase'
});
connection.connect();
Run Code Online (Sandbox Code Playgroud)

routes/index.js,我目前只有样板代码:

var express = require('express');
var router = express.Router();

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

如何connectionapp.js文件中提供对象routes/index.js

Llo*_*nks 13

我最终从app.js文件中分离出数据库连接逻辑.在一个名为的单独文件中connection.js,我有以下内容:

var mysql = require('mysql');

var connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'user',
    password: 'password',
    database: 'mydatabase'
});

module.exports = connection;
Run Code Online (Sandbox Code Playgroud)

然后在我的路线文件中,我添加

var connection = require('../connection');
Run Code Online (Sandbox Code Playgroud)

到文件的顶部,我的所有其他模块都被引入.在我的实例中,connection.js文件比我的路径文件高一级,因此../require()函数参数中.


Rob*_*kal 8

我的首选是做一些简单的依赖注入,并通过将模块包装在一个函数中将所需的资源传递到路由器:

var express = require('express');

module.exports = function (connection) {
    var router = express.Router();
    //do stuff with the connection
    return router;

}
Run Code Online (Sandbox Code Playgroud)

然后,您只需将app.js中的路由器模块实例化为一个以数据库连接为参数的函数:

app.use('/where/ever', require('./module-b')(connection)); 
Run Code Online (Sandbox Code Playgroud)

通常我将依赖项包装在一个对象中:

app.use('/where/ever', require('./module-b')({db:connection})); 
Run Code Online (Sandbox Code Playgroud)

这样,您就不必在添加依赖项时不断更改函数签名.这为您的快速应用程序提供了超轻量级的控制反转.