FsaNodeReadStream.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.FsaNodeReadStream = void 0;
  4. const stream_1 = require("stream");
  5. const Defer_1 = require("../thingies/Defer");
  6. const concurrency_1 = require("../thingies/concurrency");
  7. class FsaNodeReadStream extends stream_1.Readable {
  8. constructor(fs, handle, path, options) {
  9. super();
  10. this.fs = fs;
  11. this.handle = handle;
  12. this.path = path;
  13. this.options = options;
  14. this.__pending__ = true;
  15. this.__closed__ = false;
  16. this.__bytes__ = 0;
  17. this.__mutex__ = (0, concurrency_1.concurrency)(1);
  18. this.__file__ = new Defer_1.Defer();
  19. handle
  20. .then(file => {
  21. if (this.__closed__)
  22. return;
  23. this.__file__.resolve(file);
  24. if (this.options.fd !== undefined)
  25. this.emit('open', file.fd);
  26. this.emit('ready');
  27. })
  28. .catch(error => {
  29. this.__file__.reject(error);
  30. })
  31. .finally(() => {
  32. this.__pending__ = false;
  33. });
  34. }
  35. async __read__() {
  36. return await this.__mutex__(async () => {
  37. if (this.__closed__)
  38. return;
  39. const { file } = await this.__file__.promise;
  40. const blob = await file.getFile();
  41. const buffer = await blob.arrayBuffer();
  42. const start = this.options.start || 0;
  43. let end = typeof this.options.end === 'number' ? this.options.end + 1 : buffer.byteLength;
  44. if (end > buffer.byteLength)
  45. end = buffer.byteLength;
  46. const uint8 = new Uint8Array(buffer, start, end - start);
  47. return uint8;
  48. });
  49. }
  50. __close__() {
  51. if (this.__closed__)
  52. return;
  53. this.__closed__ = true;
  54. if (this.options.autoClose) {
  55. this.__file__.promise
  56. .then(file => {
  57. this.fs.close(file.fd, () => {
  58. this.emit('close');
  59. });
  60. return file.close();
  61. })
  62. .catch(error => { });
  63. }
  64. }
  65. // -------------------------------------------------------------- IReadStream
  66. get bytesRead() {
  67. return this.__bytes__;
  68. }
  69. get pending() {
  70. return this.__pending__;
  71. }
  72. // ----------------------------------------------------------------- Readable
  73. _read() {
  74. this.__read__().then((uint8) => {
  75. if (this.__closed__)
  76. return;
  77. if (!uint8)
  78. return this.push(null);
  79. this.__bytes__ += uint8.length;
  80. this.__close__();
  81. this.push(uint8);
  82. this.push(null);
  83. }, error => {
  84. this.__close__();
  85. this.destroy(error);
  86. });
  87. }
  88. }
  89. exports.FsaNodeReadStream = FsaNodeReadStream;
  90. //# sourceMappingURL=FsaNodeReadStream.js.map