node.jsexpressnode-mysql

NodeJS / Express - Make Available MySQL Connection Object in Router File


I have the following in my app.js file:

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

In routes/index.js, I currently have only the boilerplate code:

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

module.exports = router;

How do I make available the connection object from the app.js file in routes/index.js?


Solution

  • I ended up splitting the database connection logic from the app.js file. In a separate file called connection.js, I have the following:

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

    Then in my route file, I add

    var connection = require('../connection');
    

    to the top of the file where all my other modules are brought in. In my instance, the connection.js file is one level higher than my route file, hence the ../ in the require() function parameter.