Last active
November 5, 2019 19:50
-
-
Save midknightmare666/1751b8d7d484ea8af6f4aea7534c72ab to your computer and use it in GitHub Desktop.
Dynamically load express routes from subfolder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* main express file: app.js */ | |
const express = require('express') | |
const app = express() | |
// other middleware | |
require('./routes')(app) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* routes folder: routes/index.js */ | |
const { readdirSync } = require('fs') | |
module.exports = app => { | |
readdirSync(__dirname).forEach(file => { | |
if (file === 'index.js') return | |
const route = file.split('.')[0] | |
require(`./${route}`)(app) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* routes folder: routes/user.js */ | |
module.exports = app =>{ | |
app.get('/api/getUser', (req, res) => { | |
// .... | |
}) | |
app.post('/api/postUser', (req, res) => { | |
// .... | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment