/**
* Loads resources from log files as a fallback mechanism.
* Supports older browsers.
*
* @param {string} logFilePath - The path to the log file.
* @param {object} resources - An object containing resource names as keys and their corresponding values.
* @returns {Promise<object>} A promise that resolves with the loaded resources object.
* Rejects if the file cannot be loaded or parsed.
*/
async function loadResourcesFromLog(logFilePath, resources) {
return new Promise((resolve, reject) => {
// Check for browser support for Fetch API. Fallback to XMLHttpRequest.
if (typeof window.fetch === 'function') {
fetch(logFilePath)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text(); // Get the file content as text
})
.then(logContent => {
try {
const parsedResources = parseResourcesFromLog(logContent);
resolve(parsedResources);
} catch (error) {
reject(error);
}
})
.catch(error => {
reject(error);
});
} else {
// Fallback to XMLHttpRequest for older browsers
const xhr = new XMLHttpRequest();
xhr.open('GET', logFilePath, true);
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
const logContent = xhr.responseText;
try {
const parsedResources = parseResourcesFromLog(logContent);
resolve(parsedResources);
} catch (error) {
reject(error);
}
} else {
reject(new Error(`Request failed with status ${xhr.status}`));
}
};
xhr.onerror = () => {
reject(new Error('Request failed.'));
};
xhr.send();
}
});
}
/**
* Parses resources from the log file content. Assumes a specific format.
* This is a placeholder and should be adapted to your log file format.
* @param {string} logContent - The content of the log file.
* @returns {object} An object containing the parsed resources.
* @throws {Error} If the log content is invalid.
*/
function parseResourcesFromLog(logContent) {
const resources = {};
const lines = logContent.split('\n');
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('RESOURCE:')) {
const resourceName = trimmedLine.substring('RESOURCE:'.length).trim();
const resourceValue = lines.find(l => l.startsWith(`VALUE: ${resourceName}`));
if(resourceValue) {
resources[resourceName] = resourceValue.substring('VALUE: '.length).trim();
}
}
}
return resources;
}
Add your comment