A simple project step through part 3

Brian Gordon
4 min readMay 18, 2021

--

We left off in the last blog having just ensuring that a filename is being provided and that it actually exists on our hard drive, next its time to fill out our repository and implement some methods… Lets start with the getAll(users) method…

This will be an asynchronous method, in which we want to open the file, read its contents, parse the contents, and return the parsed content. Remember, we are storing this information as JSON which is why we will have to parse it. To get started let’s get our file opened and read. In the Node.js docs, under File System, look for read…

First thing we’ll do is await since it is an async method, then supply the path which is ‘this.filename’, then we will supply the options which is an object where we specify that we want the encoding to be ‘utf8’, if we dont specify any options, the default is set to null. Now let’s store that to variable…

and now, if we are to console.log() ‘contents’ we should see whatever is contained inside the file… so lets do it!

To test this, we will need to call getAll() below the function… and to make this as relevant as possible for you… I like to make a little helper function that will run our ‘test’ code…

As you can see, I wrapped my repo in the test function, but why?… Short of the long, some versions of node do not let top level variables make use of ‘await’. Now save the file, head over to the terminal and in the repositories directory and run the command, “node users.js’…

Perfect!… we see that an empty array is being consoled…kind of… if you remember, when we setup the writeFile, we are creating the file as an empty array…

The reason that we write it as an empty array is so that we are always working with an array of records no matter what, but right now, whats being consoled isn’t the data structure of an array, but string of two empty square brackets… The next step is parsing the contents and then returning the parsed data!

First, inside of the getAll function, we save the parsed data to the variable ‘data’ then we return that data… and now to test it… create a new variable called users, and move the console.log() from inside of the getAll() function to the test() function…

Now when the console.log runs, you should see the exact similar square bracket, but now its actually the proper data structure of an empty array.

That’s enough for this blog besides a small refactor. While the is explicit in what it’s doing, some of it is unnecessary. We can break this down into a single expression..

First wrap the value of the contents variable with JSON.parse…

which allows us to get rid of the ‘data’ variable, and now if we just return that value…

Thats the single expression that does the exact same thing! The entire file should now look something like this…

When we pick this back up in part 4 of the series, we’ll dive deep into saving records and better JSON formatting!

--

--

No responses yet