2

I have a question about the require function of Node.js, imagine we have a module that manages the connection, and many small modules that contain the routes.

An example of connection file: db.js

const mysql = require('mysql');

const connection = mysql.createConnection({
 host     : '127.0.0.1',
 user     : 'root',
 password : '',
 database : 'chat'
});

connection.connect(function(err) {
 if (err) throw err;
});

module.exports = connection;

and one of the various files to manage the routes:

const app = express();
const router = express.Router();
const db = require('./db');

router.get('/save',function(req,res){
 // some code for db
});

module.exports = router;

Imagine now to have 20 routes with the same require. How will node.js behave? How many times will my connection be created?

Eugenio
  • 25
  • 3
  • Good question. See: https://stackoverflow.com/questions/30356148/how-can-i-use-a-single-mssql-connection-pool-across-several-routes-in-an-express – lependu Nov 19 '18 at 15:46

1 Answers1

1

How many times will my connection be created?

There will be one connection, because "db.js" runs only once. The things you export get stored (module.exports) and that gets returned by every require("./db"). To verify:

 require("./db") === require("./db") // true
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151