31 lines
1 KiB
JavaScript
31 lines
1 KiB
JavaScript
|
const express = require('express');
|
||
|
const fsPromises = require('fs').promises;
|
||
|
const glob = require('glob');
|
||
|
|
||
|
(async () => {
|
||
|
const app = express();
|
||
|
const routes = await glob('**/*.js', {
|
||
|
cwd: './routes',
|
||
|
dot: true,
|
||
|
});
|
||
|
app.use(async (req, res, next) => {
|
||
|
let stats = await Promise.all([
|
||
|
fsPromises.stat(`./routes/${req.url}.js`).catch(() => "nofile"),
|
||
|
fsPromises.stat(`./routes/${req.url}/index.js`).catch(() => "nofile"),
|
||
|
]);
|
||
|
if ( req.url.endsWith('/') && stats[1] !== "nofile" ) {
|
||
|
req.url = `${req.url}index`;
|
||
|
} else if ( stats[0] === "nofile" && stats[1] !== "nofile" ) {
|
||
|
req.url = `${req.url}/index`
|
||
|
}
|
||
|
next();
|
||
|
});
|
||
|
for ( let routeScript in routes ) {
|
||
|
let route = routes[routeScript].replace(".js", "");
|
||
|
let routeObj = require(`./routes/${route}`);
|
||
|
if ( routeObj.get ) {
|
||
|
app.get(`/${route}`, routeObj.get);
|
||
|
}
|
||
|
}
|
||
|
app.listen(process.env.PORT || 3000);
|
||
|
})();
|