directory-parser.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env node
  2. // Iterate through all folders and files in a directory, return directory structure array
  3. const fs = require('fs')
  4. const path = require('path')
  5. function run(operation, relativePath) {
  6. if (!operation || !relativePath) {
  7. return { success: false, error: 'Missing required parameters: operation and directory path', exitCode: 1 }
  8. }
  9. const staticDir = process.env.STATIC_ROOT
  10. ? path.resolve(process.env.STATIC_ROOT)
  11. : path.resolve(__dirname, '..', 'static')
  12. const normalizedPath = path.normalize(relativePath).replace(/\\/g, '/')
  13. if (normalizedPath.includes('..') || normalizedPath.startsWith('/')) {
  14. return { success: false, error: 'Invalid directory path', exitCode: 1 }
  15. }
  16. const targetDir = path.resolve(staticDir, normalizedPath)
  17. if (!targetDir.startsWith(staticDir)) {
  18. return { success: false, error: 'Directory path must be within static directory', exitCode: 1 }
  19. }
  20. if (!fs.existsSync(targetDir)) {
  21. return { success: false, error: 'Directory does not exist', exitCode: 1 }
  22. }
  23. const stats = fs.statSync(targetDir)
  24. if (!stats.isDirectory()) {
  25. return { success: false, error: 'Path is not a directory', exitCode: 1 }
  26. }
  27. function readFirstLevel(dirPath) {
  28. const forders = []
  29. const files = []
  30. const entries = fs.readdirSync(dirPath, { withFileTypes: true })
  31. for (const entry of entries) {
  32. if (entry.isDirectory()) forders.push(entry.name)
  33. else files.push(entry.name)
  34. }
  35. return { forders, files }
  36. }
  37. if (operation === 'read') {
  38. const result = readFirstLevel(targetDir)
  39. return { success: true, ...result, exitCode: 0 }
  40. }
  41. return { success: false, error: `Unknown operation: ${operation}. Supported: read`, exitCode: 1 }
  42. }
  43. if (typeof module !== 'undefined' && module.exports) {
  44. module.exports = { run }
  45. }
  46. const operation = process.argv[2]
  47. const relativePath = process.argv[3]
  48. if (operation && relativePath) {
  49. const out = run(operation, relativePath)
  50. process.stdout.write(JSON.stringify(out) + '\n')
  51. process.exit(out.exitCode !== undefined ? out.exitCode : out.success ? 0 : 1)
  52. }