walk-directory.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. exports.build = void 0;
  7. const fs_1 = __importDefault(require("fs"));
  8. const readdirOpts = { withFileTypes: true };
  9. const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback) => {
  10. if (currentDepth < 0)
  11. return state.queue.dequeue(null, state);
  12. state.visited.push(crawlPath);
  13. state.counts.directories++;
  14. state.queue.enqueue();
  15. // Perf: Node >= 10 introduced withFileTypes that helps us
  16. // skip an extra fs.stat call.
  17. fs_1.default.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
  18. callback(entries, directoryPath, currentDepth);
  19. state.queue.dequeue(state.options.suppressErrors ? null : error, state);
  20. });
  21. };
  22. const walkSync = (state, crawlPath, directoryPath, currentDepth, callback) => {
  23. if (currentDepth < 0)
  24. return;
  25. state.visited.push(crawlPath);
  26. state.counts.directories++;
  27. let entries = [];
  28. try {
  29. entries = fs_1.default.readdirSync(crawlPath || ".", readdirOpts);
  30. }
  31. catch (e) {
  32. if (!state.options.suppressErrors)
  33. throw e;
  34. }
  35. callback(entries, directoryPath, currentDepth);
  36. };
  37. function build(isSynchronous) {
  38. return isSynchronous ? walkSync : walkAsync;
  39. }
  40. exports.build = build;