Files
funjia-server/Server.mts
T
2025-01-20 16:05:50 +08:00

140 lines
3.8 KiB
TypeScript

import path from 'path';
import {
dirname
} from 'path';
import {
fileURLToPath
} from 'url';
import Koa from 'koa';
import getRouter from 'koa-router';
import koaBody from 'koa-body';
import fs from "fs";
// 静态文件服务
import koaStatic from 'koa-static'
// 虚拟路径
import koaMount from 'koa-mount';
// import { ConfigHelper, DBHelper } from "funjia-server/lib/funjia-server.mjs";
import ConfigHelper from './ConfigHelper.mjs';
import DBHelper from './DBHelper.mjs';
const __dirname = dirname(fileURLToPath(
import.meta.url));
ConfigHelper.initConfig();
(async () => await DBHelper.init())();
export default CreateServer
/**
* 创建服务
* port: 服务端口号
*/
function CreateServer(port = 4873) {
const router = new getRouter();
const app = new Koa();
app.use(koaBody());
const staticPath = './static'
app.use(
koaMount('/resource/static', koaStatic(
path.join(__dirname, staticPath), {}
))
)
// app.use(koaStatic('.'));
app.use(router.routes());
app.use(router.allowedMethods());
// 初始化路由
const initRouter = (folderPath: string) => {
// 读取文件夹中的文件列表
fs.readdir(folderPath, async (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
// 筛选出.js 文件
// const jsFiles = files.filter(file => path.extname(file) === '.mjs');
for (const file of files) {
try {
const filePath = path.join(folderPath, file);
const stats = await fs.statSync(filePath);
if (stats.isDirectory()) {
await initRouter(filePath);
}
else if (stats.isFile()) {
// 构建文件的完整路径
const filePath = path.join(folderPath, file);
// 动态导入文件
const module = await import("./" + path.relative(__dirname, filePath));
// 在这里可以对导入的模块进行处理,例如调用其中的函数或使用其导出的对象
module.default(router);
// console.log(module);
}
} catch (error) {
console.error(`Error importing ${file}:`, error);
}
}
});
}
(async () => {
// 目标文件夹的路径
const folderPath = './routers';
await initRouter(folderPath);
})();
let server = null;
const startServer = () => {
server = app.listen(port, () => {
console.log('server is listen in ', port);
});
server.on('close', (err: any, socket: any) => {
server = null;
console.log('server is close');
});
}
startServer();
}
// const bH = new BackupHelper();
// 调度任务 (该模块内存占用会持续上升不建议使用,建议使用系统本身的调度任务)
// const task = cron.schedule('* */1 * * * Sunday', () => {
// console.log('running a task every 10 seconds');
// task.stop();
// server.close(async () => {
// await bH.bakFile(ConfigHelper.config.dbBak);
// startServer();
// });
// }, {
// scheduled: false,
// // https://timezonedb.com/download
// timezone: "Asia/Shanghai"
// });
// task.start();
// const delay = () => new Promise((resolve) => {
// setTimeout(() => {
// resolve(true);
// }, 1000 * 10);
// });
// (async () => {
// for (let i = 0; i < 20; i++) {
// console.log('running a task every 10 seconds');
// await delay();
// await bH.bakFile(ConfigHelper.config.dbBak);
// }
// })();