fs.ts 1.98 KB
/*
 * @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 : '读取目录失败' });
            }
        },
    },
];