json.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. const { ParserError } = require("../util/errors");
  3. module.exports = {
  4. /**
  5. * The order that this parser will run, in relation to other parsers.
  6. *
  7. * @type {number}
  8. */
  9. order: 100,
  10. /**
  11. * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
  12. *
  13. * @type {boolean}
  14. */
  15. allowEmpty: true,
  16. /**
  17. * Determines whether this parser can parse a given file reference.
  18. * Parsers that match will be tried, in order, until one successfully parses the file.
  19. * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
  20. * every parser will be tried.
  21. *
  22. * @type {RegExp|string|string[]|function}
  23. */
  24. canParse: ".json",
  25. /**
  26. * Parses the given file as JSON
  27. *
  28. * @param {object} file - An object containing information about the referenced file
  29. * @param {string} file.url - The full URL of the referenced file
  30. * @param {string} file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
  31. * @param {*} file.data - The file contents. This will be whatever data type was returned by the resolver
  32. * @returns {Promise}
  33. */
  34. async parse (file) { // eslint-disable-line require-await
  35. let data = file.data;
  36. if (Buffer.isBuffer(data)) {
  37. data = data.toString();
  38. }
  39. if (typeof data === "string") {
  40. if (data.trim().length === 0) {
  41. return; // This mirrors the YAML behavior
  42. }
  43. else {
  44. try {
  45. return JSON.parse(data);
  46. }
  47. catch (e) {
  48. throw new ParserError(e.message, file.url);
  49. }
  50. }
  51. }
  52. else {
  53. // data is already a JavaScript value (object, array, number, null, NaN, etc.)
  54. return data;
  55. }
  56. }
  57. };