I am trying to read the content of a local JSON file using vanilla Javascript. So far I have only found one method to do this, which is creating a GET request for the local file like this:
var request = new XMLHttpRequest();
request.open("GET", "localFolder/example.json", false);
request.send(null);
var data = JSON.parse(request.responseText);
Is there any other way that doesn’t require a GET request to read a local file?
// fs: manipulate files
const fs = require('fs');
// Or this way, like in jest...
// import fs from 'fs';
// path: manipulate paths
const path = require('path');
// import path from 'path';
const alerts = fs.readFileSync(
path.resolve(__dirname, './test/data/alerts.json'),
{'encoding': 'utf-8'}
);
// Of course you still need to parse the JSON, etc.
This is almost verbatim from a a jest test setup of mine. Use require/import as appropriate.
In the browser, use GET and a development web server. Otherwise you have to disable a lot of browser security to make it work.
JavaScript doesn’t really have a standard library, so almost everything is a library/package/add-on. fs is the equivalent to that bit of C#, I assume, knowing nothing of C#. You could always look at the source for fs and path to see how they do it.
The closest analogy is that JS is like C; the language will fit on a sheet of paper, but is not nearly as useful without the standard library (in C) or libraries (in JS).
This works in Chrome but not yet in Firefox (with type="module" on the script). Node has experimental support as well (with or without the flag --experimental-json-modules depending on the version I believe).
import json from './jsonData.json' assert { type: 'json' };
But it’s obviously not something you would want to implement at present time.
I’m wondering about the use case. If it’s in the browser, then you won’t be able to read local files anyway (unless you have user interaction/permission). If it’s on the server, then node’s built-in ‘fs’ is the way to go.