WF4. Express: HowTo Separate controllers

Updated: 2016-06-05

This HowTo part of a series starting with Mean stack: Preparing workflow on Windows.

It consist of notes taken from Chapter 3 in “Getting Mean With Mongo, Express, Angular, and Node“ about refactor code to controllers in Express.

WF is short for Workflow meaning a manual process in this context.

WF4. Express: HowTo Separate controllers

Express by default creates routes and views. This blog shows howto separate concerns into controllers and models, too.
01-23-2016_18-59-41

02-06-2016_18-44-01

  • $ <Ctrl-C> #Stop webserver
  • To go along with the book then we group together the \routes\ and the \views\ folders down into a new folder .\app_server\:
    • $ md app_server
    • $ move routes app_server
    • $ move views app_server
  • Create folders for \controllers\ and \models\:
    • $ cd app_server
    • $ md controllers
    • $ md models
  • Edit .\app.js – Move \routes\ and \views\ to app_server
// .\app.js:
var routes = require('./app_server/routes/index'); //L8 Move routes to subfolder
var users = require('./app_server/routes/users');

app.set('views', path.join(__dirname, 'app_server', 'views')); //L14 move views to subfolder
  • Create a new file .\app_server\controllers\main.js
    • In ST3: Ctrl+Alt-n – app_server\controllers\main.js
  • Move controller code from route index.js to controller main.js:
// .\app_server\controllers\main.js:
/* GET home page. */
module.exports.index = function(req, res) { //Ctrlr
  res.render('index', { title: 'ExpressB' }); //Return view and model (moved from index.js L6)
};

// .\app_server\routes\index.js:
var ctrlMain = require('../controllers/main') //L3: Using ctrlr
router.get('/', ctrlMain.index); //L6: Get view from ctrl

The view of the page is unchanged, but the the folders looks like this:

02-06-2016_20-30-11

The End.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: