Node.js化
import express from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// View Engine Setup
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// 静的ファイルのマウント
app.use('/static', express.static(path.join(__dirname, 'public')));
app.use('/media', express.static(path.join(__dirname, 'public/media')));
// 動的ルートの自動登録
const routeDir = path.join(__dirname, 'routes');
fs.readdirSync(routeDir).forEach(file => {
if (file.endsWith('.js')) {
import(`./routes/${file}`).then(module => {
app.use('/' + file.replace('.js', ''), module.default);
});
}
});
app.get('/', (req, res) => {
res.render('site'); // views/site.ejs を表示
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Listening at http://localhost:${port}`);
});