text.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. const { ParserError } = require("../util/errors");
  3. let TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i;
  4. module.exports = {
  5. /**
  6. * The order that this parser will run, in relation to other parsers.
  7. *
  8. * @type {number}
  9. */
  10. order: 300,
  11. /**
  12. * Whether to allow "empty" files (zero bytes).
  13. *
  14. * @type {boolean}
  15. */
  16. allowEmpty: true,
  17. /**
  18. * The encoding that the text is expected to be in.
  19. *
  20. * @type {string}
  21. */
  22. encoding: "utf8",
  23. /**
  24. * Determines whether this parser can parse a given file reference.
  25. * Parsers that return true will be tried, in order, until one successfully parses the file.
  26. * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
  27. * every parser will be tried.
  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. * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
  33. * @returns {boolean}
  34. */
  35. canParse (file) {
  36. // Use this parser if the file is a string or Buffer, and has a known text-based extension
  37. return (typeof file.data === "string" || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url);
  38. },
  39. /**
  40. * Parses the given file as text
  41. *
  42. * @param {object} file - An object containing information about the referenced file
  43. * @param {string} file.url - The full URL of the referenced file
  44. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  45. * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
  46. * @returns {string}
  47. */
  48. parse (file) {
  49. if (typeof file.data === "string") {
  50. return file.data;
  51. }
  52. else if (Buffer.isBuffer(file.data)) {
  53. return file.data.toString(this.encoding);
  54. }
  55. else {
  56. throw new ParserError("data is not text", file.url);
  57. }
  58. }
  59. };