📎 Webclip
How to include route handlers in multiple files in Express
The page describes a pattern for splitting Express route handlers across several files and loading them from a directory. A routes/index.js file reads the directory, ignores index.js, requires each other file, and calls it with app. Then app.js only needs to require(’./routes’)(app).
Reading notes#
- routes/index.js uses fs.readdirSync(__dirname) to iterate through files in the routes folder.
- The code skips index.js and derives a module name from each file name before requiring it.
- Each route file exports a function that receives app.
- A route file like routes/test1.js can register routes with app.get(’/test1/’, …).
- app.js loads the directory entry point with require(’./routes’)(app).
