-1

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)
1
  • 2
    You can't use Node.js modules in a browser. fs/promises is a Node.js module. Commented Nov 25, 2022 at 18:35

1 Answer 1

2

The module fs/promises is only avaiable in node.js and not in browsers. You should use the fetch() api which is supported by all browsers (except very old browsers like Internet Explorer). You can find a documentation on MDN.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried your suggestion but I get an error. Please see updated question
Try to type the URL in the browser and look what it returns. Please make sure that the file is available under this location.
You didn't add the file extension to the file name fetch('./configuration.json')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.