Handle JSON File in Node.JS

Introduction

In our previous article, we read a text file asynchronously. That is quite easy. This article explains the synchronous nature of node. Synchronous is the only way to read a JSON file. I assume you are familiar with JavaScript Object Notation (JSON) files.

JSON is a file format that is very reliable when transacting using APIs. And, node plays a vital role in giving JSON a new makeover. Or, you can say a better alternative to XML.

Background

So, we will do the same thing what we have done in the previous article but this time we will read the file synchronously. The JSON file is among those files that supports synchronous calls.

So, first we need a dummy JSON file.

And, save it as sample.json.

Whereas, the dummy text file would be like:

dummy text file

Save it as demo.txt.

demo


Code

First, we will deal with the synchronous call. It's a conventional way of reading any file. Either in C or PHP, they manage files synchronously. By synchronous, I mean one-way execution. Where, you have a single-flow that executes line-by-line and it will move to the next statement when the statement completes. Unlike an asynchronous call, flow-control moves to the next line without showing any concern over its completion. And, after completion it will call the specified callback function.

This shows the vital difference between blocking (synchronous) and non-blocking (asynchronous) calls.

So, let's explore synchronous calls.

explore synchronous call

And, the synchronous output will be like we expect always (single-flow).

synchronous output

So, there is nothing new in it. But, when we read any JSON file then we can manipulate more. And, filter the content of the file.

JSON file

Every time, you must use the synchronous way when you are dealing with a JSON file.

And, the output will be like:

Output

Conclusion

Keeping a constant value in a JSON file is always a good idea. Suppose, you are setting a server and you are asked to maintain the credentials of the server. Then you put those credentials in a JSON file, so you can change it in the future.

In further articles we will deal with more JSON features.

Regarding this article, if you encounter any issue then try to fix it with the attached file.

Up Next
    Ebook Download
    View all
    Learn
    View all