Home > front end >  Loading local JSON file asynchronously in JS
Loading local JSON file asynchronously in JS

Time:02-10

this is my first question here on stack overflow & I am new to coding, so I hope followed all the guidelines.

I need to find a way to load a local JSON data file asynchronously in JS and HTML. Then it needs to run as a webpage with a frontend on the server (displaying the data from the local JSON file to the user on the interface). Packages or libraries like Node.js or browserify are allowed but React.js is not.

So far I am working with the live-server npm package (which is not a must) and Node.js. I tried the following approaches:

  • Importing the file / JSON data is not an option since the JSON data has to be loaded asynchronously.

  • require() from Node.js, which does not work, because Node.js is server-side and therefore the browser (chrome) does not have access to the require() function.

  • Therefore I tried the browserify package, which lets you use require() on the browser, but I ran into the same issue as this user: browserify :- Uncaught TypeError: fs.readFileSync is not a function. But browserify does not convert fs. That's the code I had:

const fs = require('fs');

let jsonData;

fs.readFile('file.json', 'utf8', (error, data) => {
  if (error) {
    console.log('An error occured while trying to read file.json:', error);
    return;
  }
  jsonData = data;
  console.log('Parsed JSON data from data.json:', JSON.parse(data));
});

  • I also tried to work with fetch(), but my understanding is that fetch() only works for URLs and not local files.

I have tried to solve this issue for many, many hours, but couldn't figure out how to do it.

Thank you in advance :)

CodePudding user response:

You can use promises and do something like

import * as fs from 'fs';

fs.promises.readFile('file.json')
  .then((json: any) => {
    const jsonOjb: any = JSON.parse(json.toString());
  }).catch(() => {});
  •  Tags:  
  • Related