binary.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. let BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i;
  3. module.exports = {
  4. /**
  5. * The order that this parser will run, in relation to other parsers.
  6. *
  7. * @type {number}
  8. */
  9. order: 400,
  10. /**
  11. * Whether to allow "empty" files (zero bytes).
  12. *
  13. * @type {boolean}
  14. */
  15. allowEmpty: true,
  16. /**
  17. * Determines whether this parser can parse a given file reference.
  18. * Parsers that return true will be tried, in order, until one successfully parses the file.
  19. * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
  20. * every parser will be tried.
  21. *
  22. * @param {object} file - An object containing information about the referenced file
  23. * @param {string} file.url - The full URL of the referenced file
  24. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  25. * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
  26. * @returns {boolean}
  27. */
  28. canParse (file) {
  29. // Use this parser if the file is a Buffer, and has a known binary extension
  30. return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url);
  31. },
  32. /**
  33. * Parses the given data as a Buffer (byte array).
  34. *
  35. * @param {object} file - An object containing information about the referenced file
  36. * @param {string} file.url - The full URL of the referenced file
  37. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  38. * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
  39. * @returns {Buffer}
  40. */
  41. parse (file) {
  42. if (Buffer.isBuffer(file.data)) {
  43. return file.data;
  44. }
  45. else {
  46. // This will reject if data is anything other than a string or typed array
  47. return Buffer.from(file.data);
  48. }
  49. }
  50. };