file.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.file = void 0;
  7. const debug_1 = __importDefault(require("debug"));
  8. const fs_1 = require("fs");
  9. const fs_extra_1 = require("fs-extra");
  10. const notfound_1 = __importDefault(require("./notfound"));
  11. const notmodified_1 = __importDefault(require("./notmodified"));
  12. const url_1 = require("url");
  13. const debug = (0, debug_1.default)('get-uri:file');
  14. /**
  15. * Returns a `fs.ReadStream` instance from a "file:" URI.
  16. */
  17. const file = async ({ href: uri }, opts = {}) => {
  18. const { cache, flags = 'r', mode = 438, // =0666
  19. } = opts;
  20. try {
  21. // Convert URI → Path
  22. const filepath = (0, url_1.fileURLToPath)(uri);
  23. debug('Normalized pathname: %o', filepath);
  24. // `open()` first to get a file descriptor and ensure that the file
  25. // exists.
  26. const fd = await (0, fs_extra_1.open)(filepath, flags, mode);
  27. // Now `fstat()` to check the `mtime` and store the stat object for
  28. // the cache.
  29. const stat = await (0, fs_extra_1.fstat)(fd);
  30. // if a `cache` was provided, check if the file has not been modified
  31. if (cache && cache.stat && stat && isNotModified(cache.stat, stat)) {
  32. throw new notmodified_1.default();
  33. }
  34. // `fs.ReadStream` takes care of calling `fs.close()` on the
  35. // fd after it's done reading
  36. // @ts-expect-error `@types/node` doesn't allow `null` as file path :/
  37. const rs = (0, fs_1.createReadStream)(null, {
  38. autoClose: true,
  39. ...opts,
  40. fd,
  41. });
  42. rs.stat = stat;
  43. return rs;
  44. }
  45. catch (err) {
  46. if (err.code === 'ENOENT') {
  47. throw new notfound_1.default();
  48. }
  49. throw err;
  50. }
  51. };
  52. exports.file = file;
  53. // returns `true` if the `mtime` of the 2 stat objects are equal
  54. function isNotModified(prev, curr) {
  55. return +prev.mtime === +curr.mtime;
  56. }
  57. //# sourceMappingURL=file.js.map