NodeJS: Writing in FileSystem


In the past two articles we have dealt with asynchronous and synchronous for reading of a file-system's file. And, using the synchronous nature we have dealt with JSON files.

So, until now we have learned synchronous and asynchronous reading.

Now we will learn how to write in a file system.


For ages we have learn about file handling and how to do reading from and writing and appending to a text file. And, node is not new to that. Apart from that, you don't need to write a bulk of code to do a small job.

In writing, we will deal with synchronous and asynchronous solutions.


The following shows a synchronous solution:

Synchronous way

Here, we have the readFileSync() function that returns the content and it is stored inside a content variable.

And the output is like:



And execution flows in a single flow.

And when we do it asynchronously it then would be like:

asynchronous then

And, its output is like:


As you can see, "START" and "END" execute before the writing is complete.

And, ultimately when we see the output text file it would be like this.



So we have nothing new in this. If you understand the nuts & bolts of reading and writing then you can easily manage JSON files. That is a important section of Node JS.

Up Next
    Ebook Download
    View all
    View all