recursive-delete.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.recursiveDelete = recursiveDelete;
  6. var _fs = require("fs");
  7. var _path = require("path");
  8. var _isError = _interopRequireDefault(require("./is-error"));
  9. function _interopRequireDefault(obj) {
  10. return obj && obj.__esModule ? obj : {
  11. default: obj
  12. };
  13. }
  14. const sleep = (timeout)=>new Promise((resolve)=>setTimeout(resolve, timeout));
  15. const unlinkPath = async (p, isDir = false, t = 1)=>{
  16. try {
  17. if (isDir) {
  18. await _fs.promises.rmdir(p);
  19. } else {
  20. await _fs.promises.unlink(p);
  21. }
  22. } catch (e) {
  23. const code = (0, _isError).default(e) && e.code;
  24. if ((code === "EBUSY" || code === "ENOTEMPTY" || code === "EPERM" || code === "EMFILE") && t < 3) {
  25. await sleep(t * 100);
  26. return unlinkPath(p, isDir, t++);
  27. }
  28. if (code === "ENOENT") {
  29. return;
  30. }
  31. throw e;
  32. }
  33. };
  34. async function recursiveDelete(dir, exclude, previousPath = "") {
  35. let result;
  36. try {
  37. result = await _fs.promises.readdir(dir, {
  38. withFileTypes: true
  39. });
  40. } catch (e) {
  41. if ((0, _isError).default(e) && e.code === "ENOENT") {
  42. return;
  43. }
  44. throw e;
  45. }
  46. await Promise.all(result.map(async (part)=>{
  47. const absolutePath = (0, _path).join(dir, part.name);
  48. // readdir does not follow symbolic links
  49. // if part is a symbolic link, follow it using stat
  50. let isDirectory = part.isDirectory();
  51. const isSymlink = part.isSymbolicLink();
  52. if (isSymlink) {
  53. const linkPath = await _fs.promises.readlink(absolutePath);
  54. try {
  55. const stats = await _fs.promises.stat((0, _path).isAbsolute(linkPath) ? linkPath : (0, _path).join((0, _path).dirname(absolutePath), linkPath));
  56. isDirectory = stats.isDirectory();
  57. } catch (_) {}
  58. }
  59. const pp = (0, _path).join(previousPath, part.name);
  60. const isNotExcluded = !exclude || !exclude.test(pp);
  61. if (isNotExcluded) {
  62. if (isDirectory) {
  63. await recursiveDelete(absolutePath, exclude, pp);
  64. }
  65. return unlinkPath(absolutePath, !isSymlink && isDirectory);
  66. }
  67. }));
  68. }
  69. //# sourceMappingURL=recursive-delete.js.map