01 Project – Node.js / Express / MongoDB – Part 04 – Creating the configure module

We are going to create a custom module called configure. In the server folder, create a file and name it configure.js. Copy the following code into the configure.js file.

var path = require('path'),
  	routes = require('./routes'),
  	exphbs = require('express-handlebars'),
  	express = require('express'),
  	bodyParser = require('body-parser'),
  	cookieParser = require('cookie-parser'),
  	morgan = require('morgan'),
  	methodOverride = require('method-override'),
  	errorHandler = require('errorhandler');

module.exports = function(app) {
  	app.use(morgan('dev'));
  	app.use(bodyParser({
    		uploadDir:path.join(__dirname, 'public/upload/temp')
  	}));
  	app.use(methodOverride());
  	app.use(cookieParser('some-secret-value-here'));

  routes(app);

  app.use('/public/', express.static(path.join(__dirname, '../public')));
    	if ('development' === app.get('env')) {
      		app.use(errorHandler());
    	}
  	return app;
};

In the first group of lines we declare our dependencies. We can do that by declaring a variable for each module we are going to use.

Next, we have created a module that will be exported. This module is a function that takes in our app object as a parameter. The same function returns the app object after the modifications are done.

The morgan module is used for debugging the Node server.
The bodyParser module will handle the submission of forms.
The methodOverride module will handle UPDATE and PUT in old browsers since they don’t support these REST HTTP verbs.
The cookieParser module sends and receives cookies.
The errorHandler module handles any errors that occur within the middleware process.
The handlebars is a templating engine that we are going to use.

The routes(app); is a component of Express. It says that you are using a router with your server. GET, POST, PUT, and UPDATE requests can be responded.

The express.static() middleware, as its name suggests, it is used to render static content from a predefined directory.

Now, our configuration file is complete.
Next we need to call it in the index.js file. To do that, open the index.js file and add the following code:

config = require('./server/configure'),
app = config(app);

Below is the server.js file as it is at this stage.

var express = require('express');
  config = require('./server/configure'),
  app = express();
app.set('port', process.env.PORT || 3300);
app.set('views', __dirname + '/views');
app = config(app);

//app.get('/', function(req, res) {
//  res.send('There is nothing to show yet');
//});

var server = app.listen(app.get('port'), function() {
  console.log('Server up: http://localhost: ' + app.get('port'));
});

Next, we will be implementing routes and controllers.

Leave a Reply