Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you modularize Node.JS w/Express

I'm trying to modularize my node.js application (using express framework). The trouble I am having is when setting up my routes.

I am no longer able to extract the data I send to the post. (req.body is undefined). This works okay if it is all in the same file. What am I doing wrong here, and what is the best way to modularize code in node.js?

My app.js

require('./routes.js').setRoutes(app);

My route.js

exports.setRoutes = function(app){

  app.post('/ask', function(req, res, next){
    time = new Date();

    var newQuestion = {title: req.body.title, time: time.getTime(), vote:1};
    app.questions.push(newQuestion);
    res.render('index', {
      locals: {
        title: 'Questions',
        questions: app.questions
      }
    });
});
like image 538
Kiran Ryali Avatar asked Feb 20 '11 07:02

Kiran Ryali


3 Answers

A better approach:

Create a routes.js file that contains:

var index = require('./controllers/index');

module.exports = function(app) {
  app.all('/', index.index);
}

Then, from within your server.js (or however you've started your server), you'd require it as such:

require('./routes')(app);

This way you aren't creating global variables that bring with them a whole slew of issues (testability, collision, etc.)

like image 182
ctide Avatar answered Nov 07 '22 18:11

ctide


I realize someone already answered but here's what I do anyway.

app.js :

fs.readdir('./routes', function(err, files){
    files.forEach(function(fn) {
        if(!/\.js$/.test(fn)) return;
        require('./routes/' + fn)(app);
    });
});

./routes/index.js :

module.exports = function(app) {
        var data_dir = app.get('data-dir');

    app.get('/', function(req, res){
        res.render('index', {title: 'yay title'}
    });
}

Maybe someone will find this approach helpful.

like image 25
OneOfOne Avatar answered Nov 07 '22 18:11

OneOfOne


My issue was that I was declaring app in the wrong way. Instead of var app = module.exports = express.createServer();, it should have just been app = express.createServer();

And then all I needed to do in my app.js was require('./routes.js');. Now the routes file has access to the app variable and now I can just declare routes normally in the routes file.

(routes.js)

app.get('/test', function(req, res){
    console.log("Testing getter");
    res.writeHead('200');
    res.end("Hello World");
}); 
like image 2
Kiran Ryali Avatar answered Nov 07 '22 18:11

Kiran Ryali