Read a File with Node.js readFile from the File System and Parse Question and Answer

Share this video with your friends

Social Share Links

Send Tweet
Published 2 years ago
Updated 2 years ago

Now that we can read from files, we don't need to hardcode any data in our script. Instead, we can import a json file and use readFile to access questions and answers from the contents within.

We can then prompt the user with the question from the file and check the users answer against the answer that is stored.

Note: Checking the answer is just JavaScript! I set up this logic for you so we can focus on the scripting/file system side of things.

Instructor: [0:00] Here, I have a hard-coded question and answer. I want to refactor this so it's able to read from the file system. To do that I'm going to import { fs } from 'node:fs/promises'. [0:12] The file I'm going to read from is this data.JSON file. It could be an array of questions. Each question object is going to have at least the question, answer, and the ID.

[0:22] Let's refactor this. I want the data to be from awaiting fs.readFile. That's to data.JSON. When that file has been read, it will be a buffer. I need to parse that to a string.

[0:35] Now to JSON string, I wanted to be a JavaScript object, so let's parse that string. I now have an array of questions. For now, I'm just going to use the 0th question in that array and get the question and answer from it.

[0:52] Everything else now should work just the same. Node index.js, what country has more pyramids than any other? Sudan. That's right. If I get it wrong, we'll say Egypt. It'll say, "Not this time."

[1:04] One last refactor would be to change the name. Instead of pyramid, it's just going to be userAnswer because now it works for any question that's in our JSON file.

egghead
egghead

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today