Creating Modular, React-like Route Files with Express.js

Use Case: To easily divide Express routing code into independent module files.

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.

Quick Start

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.

How It Works

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:

  1. The function is called with a directory parameter chosen by the user.
  2. getPath returns the path of the directory requiring the native path module in Node.
  3. The native fs module is used to read the files and folders within the directory. As it spans the results, it is determined if each result is a directory of a file.
  4. Certain directories are ignored for middleware purposes (again, see full documentation), if not, the function is recursed on those inner directories.
  5. If a file, Express's router is directed to use and require the file.

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!

Tweet me @tylerewillis

Or send an email:

And support me on Patreon