简体   繁体   中英

How does Node's require() resolve, such that persisted database pooling in Express works?

I feel that I am lacking some basic understanding of how nodejs' architecture is put together so that the code below runs with no problems. I'm going to lay out a simple app. Can you guys help me with the questions at the end?

Notes: I am using the mysql package https://github.com/mysqljs/mysql

node app.js is run from the command line.

Inside app.js is this:

const Express = require("express");
const Path = require("path");

const app = Express();  

// Require controller modules
var book_controller = require('../controllers/bookController');
var author_controller = require('../controllers/authorController');

router.get('/book', book_controller.books_get);
router.get('/author', book_controller.authors_get);

app.listen(5000, function(){
    console.log("Server started on port 5000");
});

Inside bookController :

var getConnection = require('../config/mysql');

// Display list of all books
exports.book_get = function(req, res) {
    getConnection(function(err, con) {
        query = 'SELECT * FROM books';
        con.query(query, function(err, result) {
            if (err) throw err;
            con.release();
            res.render('page/authors', { result:result});
        });
    })        
};

Inside authorController :

var getConnection = require('../config/mysql');

// Display list of all books
exports.authors_get = function(req, res) {       
    getConnection(function(err, con) {
        query = 'SELECT * FROM authors';
        con.query(query, function(err, result) {
            if (err) throw err;
            con.release();
            res.render('page/books', { result:result});
        });
    })      
};

Inside mysql.js

var mysql = require('mysql');    
var pool = mysql.createPool({
    connectionLimit: 100,
    connectTimeout: 5000,
    acquireTimeout: 5000,
    queueLimit: 30,
    host: 'localhost',
    user: '',
    password: '',
    database: '',
    multipleStatements: true,
});    

var getConnection = function(callback) {
    pool.getConnection(function(err, connection) {
        if (err) return callback(err);
        callback(err, connection);
    });
};

pool.on('acquire', function(connection) {
    console.log('Connection %d acquired', connection.threadId);
});
module.exports = getConnection;

That's the layout. Here are the questions:

  1. How do separate files requiring the same dependency interact? Books and Author controllers both need to require and access the mysql pool, assumedly from different users. Is a new copy of the MySQL object instantiated?
  2. How does the state from the pool persist to the next connection?

How do separately required files interact? Books and Author controllers both need to require and access the mysql pool, assumedly from different users. Is a new copy of the MySQL object instantiated?

No, a new copy of the object will not be created on every call to require .

In Node, modules are loaded as needed and the resulting export object is cached for subsequent calls to require , so you'll get the exact same reference to getConnection every time you call require('../config/mysql') . The lines before module.exports = getConnection; run only the first time that the module is required.

How does the state from the pool persist to the next connection?

Because the exported getConnection is cached, that function will always refer to the same pool object, so both of your controllers are referring to the same pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM