Paradoxis Paradoxis - 1 year ago 93
Node.js Question

How to write clean, modular express.js applications

Pretty much since forever, I've stayed away from NodeJS backend development for one reason and one reason only: Almost all Express projects I've started or I've been forced to maintain end up being a huge mess where the entire website is run on a single script that's +/- 5000 lines long.

The the following example from the ExpressJS hello world page, in this form I'd end up adding more and more routes to

leading to a huge mess of code.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
res.send('Hello World!');

app.listen(3000, function () {
console.log('Example app listening on port 3000!');

What I can't seem to find, is how I could take a large express website, and turn it into a modular application where routes are small, re-usable and easily testable. If anyone has any idea of how to do this it would be greatly appreciated.

Answer Source

I generally use 1 file per route and put all my routing files in a routes folder and leverage the Router available in express.

A route file could look like this:

var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
    res.send('Hello World!');

module.exports = router;

Then in the app file, simply add:

var example = require('./routes/example');
app.use('/', example);

The routes in the routing file are relative to the route you declare in app.use.