Created
September 26, 2021 14:29
-
-
Save NathBabs/c729226d3452dd5f92e9cc80d3451016 to your computer and use it in GitHub Desktop.
Export routes folder contents through index.js using ESM exports
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
import { fileURLToPath } from 'url'; | |
const __filename = fileURLToPath(import.meta.url); | |
import express from "express"; | |
const router = express.Router(); | |
import * as fs from 'fs' | |
import path, { dirname, join } from 'path'; | |
const __dirname = dirname(__filename); | |
const basename = path.basename(__filename); | |
fs.readdir(__dirname, (err, files) => { | |
files.filter(file => { | |
return (file.indexOf(".") !== 0 && file !== basename && file.slice(-3) === ".js") | |
}).map(async file => { | |
const module = await import(`./${file}`); | |
let routes = module.default; | |
router.use(routes); | |
}) | |
}); | |
export default router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://javascript.info/modules-dynamic-imports