To make express web application modular use router factories: Module:
// greet.js
const express = require("express");
module.exports = function (options = {}) {
// Router factory
const router = express.Router();
router.get("/greet", (req, res, next) => {
res.end(options.greeting);
});
return router;
};
Application:
// app.js
const express = require("express");
const greetMiddleware = require("./greet.js");
express()
.use("/api/v1/", greetMiddleware({ greeting: "Hello world" }))
.listen(8080);