Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 app 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.

like image 632
Paradoxis Avatar asked Sep 05 '25 17:09

Paradoxis


1 Answers

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.

like image 149
Jawad Avatar answered Sep 07 '25 13:09

Jawad