← back to Letsbegin
app/api/directory/route.ts
86 lines
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
interface DirectoryNode {
name: string
path: string
type: 'file' | 'directory'
children?: DirectoryNode[]
}
const IGNORE_PATTERNS = [
'node_modules',
'.git',
'.next',
'__pycache__',
'.cache',
'dist',
'build',
'.DS_Store',
'Thumbs.db'
]
function buildTree(dirPath: string, depth = 0, maxDepth = 3): DirectoryNode | null {
try {
const stats = fs.statSync(dirPath)
const name = path.basename(dirPath)
if (IGNORE_PATTERNS.includes(name)) {
return null
}
const node: DirectoryNode = {
name,
path: dirPath,
type: stats.isDirectory() ? 'directory' : 'file'
}
if (stats.isDirectory() && depth < maxDepth) {
const entries = fs.readdirSync(dirPath, { withFileTypes: true })
const children: DirectoryNode[] = []
for (const entry of entries) {
if (IGNORE_PATTERNS.includes(entry.name)) continue
const childPath = path.join(dirPath, entry.name)
const child = buildTree(childPath, depth + 1, maxDepth)
if (child) {
children.push(child)
}
}
// Sort: directories first, then files
children.sort((a, b) => {
if (a.type !== b.type) {
return a.type === 'directory' ? -1 : 1
}
return a.name.localeCompare(b.name)
})
node.children = children
}
return node
} catch (error) {
console.error('Error building tree for:', dirPath, error)
return null
}
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const dirPath = searchParams.get('path')
if (!dirPath) {
return NextResponse.json({ error: 'Path parameter required' }, { status: 400 })
}
if (!fs.existsSync(dirPath)) {
return NextResponse.json({ error: 'Directory not found' }, { status: 404 })
}
const tree = buildTree(dirPath)
return NextResponse.json(tree)
}