file.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. const fs = require("fs");
  3. const { ono } = require("@jsdevtools/ono");
  4. const url = require("../util/url");
  5. const { ResolverError } = require("../util/errors");
  6. module.exports = {
  7. /**
  8. * The order that this resolver will run, in relation to other resolvers.
  9. *
  10. * @type {number}
  11. */
  12. order: 100,
  13. /**
  14. * Determines whether this resolver can read a given file reference.
  15. * Resolvers that return true will be tried, in order, until one successfully resolves the file.
  16. * Resolvers that return false will not be given a chance to resolve the file.
  17. *
  18. * @param {object} file - An object containing information about the referenced file
  19. * @param {string} file.url - The full URL of the referenced file
  20. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  21. * @returns {boolean}
  22. */
  23. canRead (file) {
  24. return url.isFileSystemPath(file.url);
  25. },
  26. /**
  27. * Reads the given file and returns its raw contents as a Buffer.
  28. *
  29. * @param {object} file - An object containing information about the referenced file
  30. * @param {string} file.url - The full URL of the referenced file
  31. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  32. * @returns {Promise<Buffer>}
  33. */
  34. read (file) {
  35. return new Promise(((resolve, reject) => {
  36. let path;
  37. try {
  38. path = url.toFileSystemPath(file.url);
  39. }
  40. catch (err) {
  41. reject(new ResolverError(ono.uri(err, `Malformed URI: ${file.url}`), file.url));
  42. }
  43. // console.log('Opening file: %s', path);
  44. try {
  45. fs.readFile(path, (err, data) => {
  46. if (err) {
  47. reject(new ResolverError(ono(err, `Error opening file "${path}"`), path));
  48. }
  49. else {
  50. resolve(data);
  51. }
  52. });
  53. }
  54. catch (err) {
  55. reject(new ResolverError(ono(err, `Error opening file "${path}"`), path));
  56. }
  57. }));
  58. }
  59. };