remove-forder.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * fun 结点:remove-folder(脚本名 remove-forder 为历史拼写)
  3. * inVars[0] 或字段 path:目录路径(相对当前流程目录或绝对路径)
  4. * 默认递归删除目录及内容(等同 rm -rf)。若仅需删除空目录,设 recursive 为 0 / false / no / empty-only
  5. */
  6. const path = require('path')
  7. const fs = require('fs')
  8. function buildAbsolutePath (p, folderPath) {
  9. if (p == null || p === '') return null
  10. const s = typeof p === 'string' ? p.trim() : String(p).trim()
  11. if (!s) return null
  12. if (path.isAbsolute(s) || /^[A-Za-z]:/.test(s)) return path.normalize(s)
  13. return folderPath ? path.join(folderPath, s) : path.resolve(s)
  14. }
  15. /** 未指定时默认 true(非空目录也可删);0 / false / no / empty-only 则仅删空目录 */
  16. function parseRecursive (raw) {
  17. if (raw == null || raw === '') return true
  18. const t = String(raw).trim().toLowerCase()
  19. if (t === '') return true
  20. if (t === '0' || t === 'false' || t === 'no' || t === 'empty-only') return false
  21. return true
  22. }
  23. /**
  24. * @param {{ path?: string, dirPath?: string, recursive?: string, folderPath?: string }} input
  25. */
  26. async function executeRemoveFolder ({ path: p, dirPath, recursive, folderPath }) {
  27. const rel = p != null && String(p).trim() !== '' ? p : dirPath
  28. if (rel == null || String(rel).trim() === '') {
  29. return { success: false, error: 'remove-folder 缺少 path(inVars[0] 或字段 path)' }
  30. }
  31. const abs = buildAbsolutePath(String(rel).trim(), folderPath)
  32. if (!abs) return { success: false, error: 'remove-folder 路径无效' }
  33. const rec = parseRecursive(recursive)
  34. try {
  35. if (!fs.existsSync(abs)) return { success: true, skipped: true, path: abs }
  36. const st = fs.statSync(abs)
  37. if (!st.isDirectory()) return { success: false, error: 'remove-folder 目标不是目录' }
  38. fs.rmSync(abs, { recursive: rec, force: false })
  39. } catch (e) {
  40. if (!rec && (e.code === 'ENOTEMPTY' || e.code === 'EISDIR')) {
  41. return { success: false, error: '目录非空或无法以非递归方式删除:请去掉 recursive=false/0,或不要设置 recursive(默认递归删除整目录)' }
  42. }
  43. return { success: false, error: e && e.message ? e.message : String(e) }
  44. }
  45. return { success: true, path: abs }
  46. }
  47. module.exports = { executeRemoveFolder }