1. /**
  2. * Loads resources from log files as a fallback mechanism.
  3. * Supports older browsers.
  4. *
  5. * @param {string} logFilePath - The path to the log file.
  6. * @param {object} resources - An object containing resource names as keys and their corresponding values.
  7. * @returns {Promise<object>} A promise that resolves with the loaded resources object.
  8. * Rejects if the file cannot be loaded or parsed.
  9. */
  10. async function loadResourcesFromLog(logFilePath, resources) {
  11. return new Promise((resolve, reject) => {
  12. // Check for browser support for Fetch API. Fallback to XMLHttpRequest.
  13. if (typeof window.fetch === 'function') {
  14. fetch(logFilePath)
  15. .then(response => {
  16. if (!response.ok) {
  17. throw new Error(`HTTP error! status: ${response.status}`);
  18. }
  19. return response.text(); // Get the file content as text
  20. })
  21. .then(logContent => {
  22. try {
  23. const parsedResources = parseResourcesFromLog(logContent);
  24. resolve(parsedResources);
  25. } catch (error) {
  26. reject(error);
  27. }
  28. })
  29. .catch(error => {
  30. reject(error);
  31. });
  32. } else {
  33. // Fallback to XMLHttpRequest for older browsers
  34. const xhr = new XMLHttpRequest();
  35. xhr.open('GET', logFilePath, true);
  36. xhr.onload = () => {
  37. if (xhr.status >= 200 && xhr.status < 300) {
  38. const logContent = xhr.responseText;
  39. try {
  40. const parsedResources = parseResourcesFromLog(logContent);
  41. resolve(parsedResources);
  42. } catch (error) {
  43. reject(error);
  44. }
  45. } else {
  46. reject(new Error(`Request failed with status ${xhr.status}`));
  47. }
  48. };
  49. xhr.onerror = () => {
  50. reject(new Error('Request failed.'));
  51. };
  52. xhr.send();
  53. }
  54. });
  55. }
  56. /**
  57. * Parses resources from the log file content. Assumes a specific format.
  58. * This is a placeholder and should be adapted to your log file format.
  59. * @param {string} logContent - The content of the log file.
  60. * @returns {object} An object containing the parsed resources.
  61. * @throws {Error} If the log content is invalid.
  62. */
  63. function parseResourcesFromLog(logContent) {
  64. const resources = {};
  65. const lines = logContent.split('\n');
  66. for (const line of lines) {
  67. const trimmedLine = line.trim();
  68. if (trimmedLine.startsWith('RESOURCE:')) {
  69. const resourceName = trimmedLine.substring('RESOURCE:'.length).trim();
  70. const resourceValue = lines.find(l => l.startsWith(`VALUE: ${resourceName}`));
  71. if(resourceValue) {
  72. resources[resourceName] = resourceValue.substring('VALUE: '.length).trim();
  73. }
  74. }
  75. }
  76. return resources;
  77. }

Add your comment