I am trying to read a json file into my Javascript program.
configuration.json
{
"ProxyURLS": ["xxxx","xxxx"],
"DatabaseURLS": ["xxxx"]
}
The JSON file is in the same directory as the index.html
Index html
<!DOCTYPE html>
<html>
<head>
<title>QUBGrader</title>
<script type="text/javascript">
import { readFile } from "fs/promises";
//Define path for configuration readFile
path = "./configuration"
//read file get json
async function readJsonFile(path) {
const file = await readFile(path, "utf8");
return JSON.parse(file);
}
readJsonFile("./package.json").then((data) => {
console.log(data);
getProxyURL(data);
});
function getProxyURL(data)
{
console.log("here")
console.log(data)
}
... file continues ...
I want to obtain the JSON object and pass it to the getProxyURL function.
I get this error when I do not include the import statement
(index):13 Uncaught (in promise) ReferenceError: readFile is not defined
at readJsonFile ((index):13:16)
at (index):17:1
I get this error when I do include the import statement
Uncaught SyntaxError: Cannot use import statement outside a module (at (index):8:1)
From googling the error (https://bobbyhadz.com/blog/javascript-syntaxerror-cannot-use-import-statement-outside-module#:~:text=The%20%22SyntaxError%3A%20Cannot%20use%20import,json%20for%20Node.)
It seems that I need to define a "module", but I am not sure how to do that within a single .html file.
Any help appreciated.
I followed advice from this question: Dynamic import with json file doesn't work typescript
EDIT
After implementing suggested solution:
function readJson () {
// http://localhost:8080
fetch('./configuration')
.then(response => {
if (!response.ok) {
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(json => {
getProxyURL(json);
//console.log(this.users);
})
.catch(function () {
this.dataError = true;
})
};
readJson();
I get this error:
Failed to load resource: the server responded with a status of 404 (Not Found)
fs/promisesis a Node.js module.