I’m trying to convert a small (single page) PHP app to Javascript but having trouble accessing the contents of the JSON file.
I think it’s down to how I’ve written the JS, but as an example:
async function fetchLocalFile(filePath) {
try {
const response = await fetch(filePath);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const fileContents = await response.text();
return fileContents;
} catch (error) {
console.error('Error fetching the file:', error);
}
}
// Usage example
const filePath = 'example.json';
fetchLocalFile(filePath).then(contents => {
console.log(contents); // this works, I get the whole json file to console
});
console.log(contents["name"][0]); // Error: contents not defined.
So my questions:
- How do I get contents to exist outside the fetchLocalFile request?
- I’d like to use this on other, similar pages. How would I move the function to another JS file (I’d like to make it as a shareable ‘utility’ function set, separate to whatever JS code I’m writing per app to save me re-writing the function).