I am importing a JSON file from my website's own directory on the front-end. After a user clicks a button, this code is executed in the browser:
const file = await import('./path-to-file')
The file is exceptionally small - only 4KB. Yet using console.time()
is showing that it takes about 300ms to execute this command. I have checked my own web speed which comes out at 74Mb/s. I am using Netlify to deploy the website and Bitcatcha is saying the server is 'exceptionally fast' with a response time of 133ms. I'm not sure exactly how the response time fits into all this - but all in all, 300ms seems absurdly long to be transferring just 4KB of data.
Why does it take so long, and what can be done to make it faster?
Try doing:
const file = await require("./path-to-file"); //instead of import();
I believe that it takes so long because of the use of await , so if the above does not work, try removing the await , because what await does is it stops async function execution until the require(); has resolved. If the code continues running as you get the content of the file, the overall time should shrink. If none of the above works, try this:
const fs = require("fs");
fs.readFile("./path-to-file","utf-8",(err,d)=>{
d = JSON.parse(d);
//Then you do whatever you wanted to do with the file here
});
Is this js from the browser or server side?
I'm assuming browser from context, the reason it's so slow is because it like it states, waits for the file to load. The accepted answer does make it faster, but the issue then is that the json file isn't guaranteed to be processed after that line of code.
Async code is a big thing in js and other languages so I recommend looking further into this but here's some examples:
Let's say this is the json file1
{
count: 2
}
Here's the js file
const data = import("path-to-json");
//it immediately goes to the next code
console.log(data.count);
// => undefined or error, since it hasn't finished resolving it
if you wish to access it you would either have to use .then
or await
let data;
import("path-to-json").then(d => {
data = d;
//now you can use data
console.log(data.count)
// => 2
});
//it has still moved on to the next code
//so you still can't use data here
console.log(data.count)
// => undefined or error
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.