Call twice the app variable in an express application

I have a file where I call all the require modules called 'app.js'

var express = require('express');
...
var app = express();

...

var routes = require('ruotes/index.js)

use('/', routes);

module.exports = app;

I call the index.js where I have all the routes

routes/index.js

var express = require('express');
var app = express();

/* import controllers */
var indexController = require('../controllers/index');

app.route('/')
   .get(indexController.index);

module.exports = app;

The problem is I have two variables called app and I call twice express(). Does it exist a more elegant way to handle this situation? Maybe I could call the variable in router file in another way?

You are currently using a technique that is known as submounting.

If you want to avoid creating different instances of Express, you will have to pass your unique instance of Express as a parameter to your router, meaning that your index.js needs to export a function that accepts your app as a parameter.

Something like :

//=== routes/index.js

/* import controllers */
var indexController = require('../controllers/index');



module.exports = function(app){
    app.route('/').get(indexController.index);
};

Doing so will allow you to keep the same instance of Express in your entire Web App. Since you exported a function in index.js, you need to call it in app.js.

var express = require('express');
...
var app = express();

...

var routes = require('routes/index.js)(app)

module.exports = app;

You can use the same technique for routes, modules, models etc... This technique will allow you to avoid re-requiring modules, and instantiating them, but you will need to write extra-bits to make sure your variables are passed from one side of your app to the other. Because of this, some prefer using the submounting technique, and requiring modules only where they are needed.