0
\$\begingroup\$

This is my app.js:

'use strict';
global.config = require('./config/environment/config');
global.i18n = require('./config/locales/config');
var express = require('express');
var app = express();
app.locals = global.config;
var passport = require('passport');
var session = require('express-session');
var load = require('express-load');
var flash = require('express-flash');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.set('views', path.join(__dirname, 'views'))
 .set('view engine', global.config.site.html.engine)
 .set('port', process.env.PORT || 3000)
 .set('env', process.env.NODE_ENV || 'development')
 .set('ip', process.env.IP || "0.0.0.0")
app.use(favicon(__dirname + '/assets/favicon.ico'))
 .use(logger('dev'))
 .use(bodyParser.json())
 .use(bodyParser.urlencoded({ extended: false }))
 .use(flash())
 .use(cookieParser())
 .use(express.static(path.join(__dirname, 'assets')))
 .use(session({ secret: 'keyboard cat' }))
 .use(passport.initialize())
 .use(passport.session());
var middlewares = require('./middlewares/config')(app);
load('models')
 .then('controllers')
 .then('routes')
 .into(app);
var prototypes = require('./helpers/prototypes');
mongoose.connect('mongodb://' + global.config.db.credentials + '@' + global.config.db.url + '/' + global.config.db.name, function(req, res) {
 console.log('db ok');
});
module.exports = app;

One aspect that annoys me is that I would prefer to have all the require() calls together. However, if I move middlewares and prototypes before app.set(), the code will break. Is there a better way to organize this code?

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Feb 9, 2015 at 20:10
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

You can always move the require() call for middlewares up. You're not doing anything with the returned value from calling it on app.

var middlewares = require('./middlewares/config');
app.set(.....)
app.use(.....)
middlewares(app)

I'm assuming prototypes does some hacks with the global namespace. If so, then there's not much you can do about it. That's not really good practice though.

answered Jul 7, 2017 at 2:28
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.