Skip to content

Instantly share code, notes, and snippets.

@NathBabs
Created September 26, 2021 14:29
Show Gist options
  • Save NathBabs/c729226d3452dd5f92e9cc80d3451016 to your computer and use it in GitHub Desktop.
Save NathBabs/c729226d3452dd5f92e9cc80d3451016 to your computer and use it in GitHub Desktop.
Export routes folder contents through index.js using ESM exports
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;
@NathBabs
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment