React takes a simple approach to routing - you simply put files into a 'pages' folder and name them according to your desired front-end URL directory. The user can then access the contents of the file via the appropriate URL path.
Having built my fair share of Node.js Express applications with larger-than-desired (and not very modular) routing files, I wanted to create a similar approach to React that I could use with my Express apps.
The express-modularity app, available in NPM via npm i express-modularity lets a programmer predetermine the directory containing the routes files and then create one or multiple Express routes to be placed in those files.
This helps the programmer build their applications in a modular way which is what makes Node.js so effective.
A user can get up and running with express-modularity by first requiring the module in their project, calling it on the chosen directory containing the route files, and then telling the Express application to use the function's returned routes:
JavaScript
const modularity = require('express-modularity')
modularity.call('routes')
app.use(modularity.router)
Full documentation (including functionality for including middleware, global middleware and components) is available at the module's public NPM and Github pages, but I wanted to give a quick overview of how it works behind the scenes.
Here's the function call and below I'll explain how it works:
JavaScript
function call(directory) {
let path = getPath(directory)
...
require("fs").readdirSync(path, {withFileTypes: true}).forEach(function(file) {
if (file.isDirectory()) {
if (!ignoreDirectories.includes(file.name)) call(directory + '/' + file.name)
} else {
if (file.name.charAt(0) !== '.') router.use(urlDirectory, require(path + '/' + |file.name))
}
})
}
A breakdown of the above function:
I left certain things out - nested directories and URL directory paths and middleware. You can see the raw code at Github.
Ultimately, express-modularity isn't more than a loader of files within a directory. However, staying true to modularity, I didn't want to have to recreate this loader with each project. So yay for modular programming!