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.