fs.ts
1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @Author: liimin 17653212@qq.com
* @Date: 2026-09-15 16:31:34
* @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2026-09-15 17:02:32
* @FilePath: \coderio\apps\server\src\routes\fs.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import path from 'node:path';
import { existsSync, statSync, readdirSync } from 'node:fs';
import type { Route } from './context';
import { listRoots, FS_NOISE } from '../http-utils';
/** GET /api/fs/list:服务端目录浏览器,驱动前端目录选择器。 */
export const fsRoutes: Route[] = [
{
method: 'GET',
path: '/api/fs/list',
handle: ({ ctx, res, url }) => {
const dirParam = (url.searchParams.get('dir') || '').trim();
try {
if (!dirParam) {
ctx.sendJson(res, 200, { path: null, parent: null, dirs: listRoots(), isRoot: true });
return;
}
const abs = path.resolve(dirParam);
if (!existsSync(abs) || !statSync(abs).isDirectory()) {
ctx.sendJson(res, 400, { error: `目录不存在:${abs}` });
return;
}
const entries = readdirSync(abs, { withFileTypes: true });
const dirs = entries
.filter((e) => e.isDirectory() && !FS_NOISE.has(e.name))
.map((e) => e.name)
.sort((a, b) => a.localeCompare(b));
const parent = path.dirname(abs);
ctx.sendJson(res, 200, {
path: abs,
parent: parent !== abs ? parent : null,
dirs,
isRoot: false,
});
} catch (e) {
ctx.sendJson(res, 500, { error: e instanceof Error ? e.message : '读取目录失败' });
}
},
},
];