opendir.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.opendir = exports.CustomDir = void 0;
  4. const tslib_1 = require("tslib");
  5. const errors = tslib_1.__importStar(require("../errors"));
  6. class CustomDir {
  7. constructor(path, nextDirent, opts = {}) {
  8. this.path = path;
  9. this.nextDirent = nextDirent;
  10. this.opts = opts;
  11. this.closed = false;
  12. }
  13. throwIfClosed() {
  14. if (this.closed) {
  15. throw errors.ERR_DIR_CLOSED();
  16. }
  17. }
  18. async *[Symbol.asyncIterator]() {
  19. try {
  20. let dirent;
  21. // eslint-disable-next-line no-cond-assign
  22. while ((dirent = await this.read()) !== null) {
  23. yield dirent;
  24. }
  25. }
  26. finally {
  27. await this.close();
  28. }
  29. }
  30. read(cb) {
  31. const dirent = this.readSync();
  32. if (typeof cb !== `undefined`)
  33. return cb(null, dirent);
  34. return Promise.resolve(dirent);
  35. }
  36. readSync() {
  37. this.throwIfClosed();
  38. return this.nextDirent();
  39. }
  40. close(cb) {
  41. this.closeSync();
  42. if (typeof cb !== `undefined`)
  43. return cb(null);
  44. return Promise.resolve();
  45. }
  46. closeSync() {
  47. var _a, _b;
  48. this.throwIfClosed();
  49. (_b = (_a = this.opts).onClose) === null || _b === void 0 ? void 0 : _b.call(_a);
  50. this.closed = true;
  51. }
  52. }
  53. exports.CustomDir = CustomDir;
  54. function opendir(fakeFs, path, entries, opts) {
  55. const nextDirent = () => {
  56. const filename = entries.shift();
  57. if (typeof filename === `undefined`)
  58. return null;
  59. return Object.assign(fakeFs.statSync(fakeFs.pathUtils.join(path, filename)), {
  60. name: filename,
  61. });
  62. };
  63. return new CustomDir(path, nextDirent, opts);
  64. }
  65. exports.opendir = opendir;