Skip to content Skip to sidebar Skip to footer

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 main

Solution 1:

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.

Post a Comment for "How To Write Clean, Modular Express.js Applications"