New to ES6 coming from using mostly early jquery, then fetch, and more recently more require and less module imports.
Anyway, this is presented in a closed thread as the more modern solution, without the explanation of actually including the try catch
Answer for 2021, using ES6 module syntax and async/await
In modern JavaScript, this can be done as a one-liner, without the need to install additional packages:
import { readFile } from 'fs/promises';
let data = JSON.parse(await readFile("filename.json", "utf8"));
Add a try/catch block to handle exceptions as needed.
In my case, the file isn't a module so I'm actually importing async readFile with require: const { readFile } = require('fs').promises;
Then of course I want to parse the data when it arrives and do something with it. Only the syntax has not yet sunk in.
Where to put the success function in the following structure:
const data = JSON.parse(
await readFile(new URL('./its_data.json', import.meta.url));
);
console.log(data);
What is in your opinion the ultimate way to handle this? Also, what's with the import.meta.url, and the new URL() class instantiation? Where would the try catch go in here?
Comments?