Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS and Express - separate my controllers and models

I'm building my first Express app. It's a bit messy as my controllers and my models are all in the same place: the app.js file. Is there a way that I can separate those? Even artificially, by creating different files and then using some third party program to compile them into the app.js file.

like image 382
sf89 Avatar asked Nov 14 '13 12:11

sf89


People also ask

Why should you separate Express app and server in NodeJS?

Faster testing execution. Getting wider coverage metrics of the code. Allows deploying the same API under flexible and different network conditions. Better separation of concerns and cleaner code.

Does ExpressJs follow MVC?

ExpressJs does not follow any specific pattern. You are free to structure your project as you wish.

What is the relationship between NodeJS and ExpressJs?

NodeJS is an event-driven, non-blocking I/O model using JavaScript as its main language. It helps to build scalable network applications. Express is a minimal and flexible Node. js web application framework that provides a robust set of features for web and mobile applications.


1 Answers

First of all, you need to create your controllers and model folders.

You can use a module called express-load which can be used to autoload models, routes, schemas, configs, controllers, object maps... etc...

in your main file, mine is called app.js you load them right before start the server code line.. it should look like

//requires....
var load = require('express-load');

//your code 

load('models')
.then('controllers')
.then('routes')
.into(app);

http.createServer(app).listen(app.get('port'), function(){
    console.log("Express listening on port "+ app.get('port'));
});

module.exports = app;

Then, your view folder you can create folders to keep your code organized, then subfolders, I created a folder called home, and inside of it my index view.

In my controllers folder I created a js file called home.js, and which will look for my index view:

module.exports = function(app){

    var HomeController = {
        index: function(req, res){
            res.render('home/index');
        }
    };
    return HomeController;
}

At last in your routes folder, you can set your application routes, each view needs to be specified in your controller. My file for routes its called home.js

module.exports = function(app){
    var home = app.controllers.home;

    app.get('/', home.index);
}
like image 97
Jessica Thedoc Avatar answered Oct 03 '22 15:10

Jessica Thedoc