-1

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?

F. Certainly.
  • 181
  • 14
  • What "in a closed thread" are you referring to? Do you have a link? – Bergi Aug 22 '21 at 19:55
  • It's unclear what you mean by "*Where to put the success function?*" – Bergi Aug 22 '21 at 19:57
  • There is no "ultimate method". It always depends on your constraints (and you haven't even stated your environment, although it looks like nodejs). You say you're not even using module syntax, which doesn't sound very 2021. Either way, asking for opinions and comments is off-topic on StackOverflow. Do you have a concrete problem or does the code already work for you? – Bergi Aug 22 '21 at 20:00
  • "*what's with the import.meta.url, and the new URL() class instantiation?*" - did you read the docs for these? – Bergi Aug 22 '21 at 20:00
  • https://www.py4u.net/discuss/1191703 in answer 6 he doesn't specify where to add the try catch structure. By 'success function' I'm referring to successful retrieving the data that is being awaited on with readFile. Yes, I read some docs for import.meta.url, but not likely the correct docs. There is concrete problem, retrieving data using node from the working directory, parsing it and transforming it using the structure shown, or a better modern one. – F. Certainly. Aug 22 '21 at 21:37
  • Uh, that's not a "closed thread", that's just a copy of https://stackoverflow.com/q/10011011/1048572. You could just leave a comment on [that answer](https://stackoverflow.com/a/66602707/1048572). – Bergi Aug 22 '21 at 22:04
  • And in your snippet, `console.log(data)` is the "success function". – Bergi Aug 22 '21 at 22:06
  • that snippet brought up errors – F. Certainly. Aug 22 '21 at 22:09
  • Which errors??? – Bergi Aug 22 '21 at 22:09
  • SyntaxError: missing ) after argument list – F. Certainly. Aug 22 '21 at 22:11
  • That's weird. In what line? Is that the actual code you execute? Can you post the whole script? – Bergi Aug 22 '21 at 22:14
  • This was the entire script `index.js` `const { readFile } = require('fs').promises; const data = JSON.parse( await readFile( new URL('./its_data.json', import.meta.url) ); ); console.log(data);` , the json file is valid json array of arrays of product data, and the node version is the latest version, being called from `node .` – F. Certainly. Aug 22 '21 at 22:22
  • Oh, I see now, you've got a semicolon too much. There should be none inside the `JSON.parse(…)` call. – Bergi Aug 22 '21 at 22:30
  • stack overflow is complaining about long threads, but there is still the same node error, so apparently there is another problem with that structure, even with the entire url method removed. `const { readFile } = require('fs').promises; const data = JSON.parse( await readFile('./its_data.json') ); console.log(data);` – F. Certainly. Aug 22 '21 at 22:41

1 Answers1

0

So as stated in comments there is no ultimate way to do it, and you should not be looking for one. Use what works for you. I will show the way that is the closest one for the code you provided, this is by far not the only one and I will not list all of them, because it will take a little over an eternity.

Anyway, first you shouldn't use URL if you don't know what it is yet. You can read about it on the internet, as well as about import.meta.url before using them. But this is not necessary in this case. readFile actually can accept a simple string that is a path to the file you want to read. So use readFile('./its_data.json', 'utf8')

Second, there is no success function because this code uses promises. You can opt out of promises by importing normal readFile, then there will be success function

const {readFile} = require('fs')

readFile('./its_data.json', 'utf8', (error, data) => {
  if(error) { /* handle file reading error */ }

  try {
    const json = JSON.parse(data)
    // do something with data
  } catch(e) {
    // handle json parsing or your code errors
  }
})

If you want to use promises (which you probably do), then you should probably first read about the way they work somewhere on the internet, then in your code you would do something like this:

const {readFile} = require('fs').promises

readFile('./its_data.json', 'utf8')
  .then(data => {
    const json = JSON.parse(data)
    // Do something with data
  })
  .catch(error => {
    // Handle file reading or json parsing or your code errors
  })

You can read more about readFile function in NodeJS documentation

Alex Chashin
  • 3,129
  • 1
  • 13
  • 35
  • I can retrieve the data and operate on it in a variety of ways (fetch for example), what I'm after with this question is to use the structure suggested in the question `const data = JSON.parse( await readFile(new URL('./its_data.json', import.meta.url)); );` In that structure it seems the .then is implicit, or is that how the await is resolved? If you have a link to decent docs on `new URL` and `import.meta.url` please post – F. Certainly. Aug 22 '21 at 21:43
  • @F.Certainly. Yes, `await` is the same as `.then()` but without nested callbacks. As for docs, see https://nodejs.org/api/esm.html#esm_import_meta_url and https://nodejs.org/api/url.html#url_new_url_input_base – Bergi Aug 22 '21 at 22:09
  • It looks like in this case `await readFile(new URL('./its_data.json', import.meta.url));` import.meta.url is the 'base' argument for url, however, the url module itself, unless it's included in fs.promise library was not even imported. – F. Certainly. Aug 22 '21 at 22:16
  • @F.Certainly. `URL` is a global since nodejs v10. But sure, you might want to explicitly import it – Bergi Aug 22 '21 at 22:46
  • Does stack overflow have a chat app? – F. Certainly. Aug 22 '21 at 23:20
  • @F.Certainly. please read some tutorials on promises and async/await syntax on the internet – Alex Chashin Aug 23 '21 at 14:35
  • "Reading is to the mind what exercise is to the body." ~ Joseph Addison – F. Certainly. Aug 24 '21 at 00:11