| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- #!/usr/bin/env node
- // Iterate through all folders and files in a directory, return directory structure array
- const fs = require('fs')
- const path = require('path')
- function run(operation, relativePath) {
- if (!operation || !relativePath) {
- return { success: false, error: 'Missing required parameters: operation and directory path', exitCode: 1 }
- }
- const staticDir = process.env.STATIC_ROOT
- ? path.resolve(process.env.STATIC_ROOT)
- : path.resolve(__dirname, '..', 'static')
- const normalizedPath = path.normalize(relativePath).replace(/\\/g, '/')
- if (normalizedPath.includes('..') || normalizedPath.startsWith('/')) {
- return { success: false, error: 'Invalid directory path', exitCode: 1 }
- }
- const targetDir = path.resolve(staticDir, normalizedPath)
- if (!targetDir.startsWith(staticDir)) {
- return { success: false, error: 'Directory path must be within static directory', exitCode: 1 }
- }
- if (!fs.existsSync(targetDir)) {
- return { success: false, error: 'Directory does not exist', exitCode: 1 }
- }
- const stats = fs.statSync(targetDir)
- if (!stats.isDirectory()) {
- return { success: false, error: 'Path is not a directory', exitCode: 1 }
- }
- function readFirstLevel(dirPath) {
- const forders = []
- const files = []
- const entries = fs.readdirSync(dirPath, { withFileTypes: true })
- for (const entry of entries) {
- if (entry.isDirectory()) forders.push(entry.name)
- else files.push(entry.name)
- }
- return { forders, files }
- }
- if (operation === 'read') {
- const result = readFirstLevel(targetDir)
- return { success: true, ...result, exitCode: 0 }
- }
- return { success: false, error: `Unknown operation: ${operation}. Supported: read`, exitCode: 1 }
- }
- if (typeof module !== 'undefined' && module.exports) {
- module.exports = { run }
- }
- const operation = process.argv[2]
- const relativePath = process.argv[3]
- if (operation && relativePath) {
- const out = run(operation, relativePath)
- process.stdout.write(JSON.stringify(out) + '\n')
- process.exit(out.exitCode !== undefined ? out.exitCode : out.success ? 0 : 1)
- }
|