Skip to main content

BLOCKING VS NON-BLOCKING FILE WRITE IN NODEJS

this article we’ll be taking the simplest of examples of writing to and reading from files in NodeJS and understand how does blocking and non-blocking code work in NodeJS.

Why blocking and non-blocking

We’re not going to go into too much depth in this article about threads and how Node works under the hood but to grasp the concept of blocking and non-blocking code you should know just one thing – Node is single-threaded, i.e, only one process can be run on it at a single time. For example, you write a piece of code for 5 users to interact with, line 8 of your code takes say 2 seconds to execute. If a user A hits line 8 of the code during his process execution and at the same time a user B also tries to execute the same program, that line 8 will be blocking the execution of user B’s program as well.
A piece of code that blocks the execution of any other code beyond it till it itself gets executed is what we refer to as blocking code. This blocking code could be anything – reading from a DB, some complex mathematical operation, some I/O operation, anything.
What is important is to know that blocking code is not good code in NodeJS. We do not want to stall other users for some code someone else is executing. Now, in some super edge case you might specifically want to write blocking code but usually that’s not what we want and what we aim for. Let us now see with this file read-write operation how blocking and non-blocking code works in NodeJS.

Blocking Way

The blocking way also called the synchronous way is one in which the code gets executed line by line, ie, the code in the next line will not be executed until the code in the previous line has finished execution.
In this method we use the in-built function of the fs module called readFileSync to read the contents of a file called mytext.txt and store it in the variable called inputText. Later we write that content plus an additional line to a file called outputfile.txt .
The functions readFileSync and writeFileSync as the names suggest are synchronous functions, ie, these are blocking code. What this means is that if the file we are reading is super large and takes 5 seconds then any code ahead of it won’t be executed for those 5 seconds, actually no code in this node process would be executed for those 5 seconds.
See this new code, yeah it’s new ðŸ˜› . I have changed the newText that we write here to a different independent of inputText. Now, here we are not dependent on the value of inputText to write to the outputfile.txt . But because this code is blocking, we won’t be able to write before the reading process is over. You can check it by console logging the value of inputText just before the write operation ! It will be present there.

Non-blocking way

This on the other hand is some non-blocking code. Yes, I’ve used callbacks as those are understood by the majority and even those who still haven’t had exposure to async/await.
In this function, what you’ll notice is that the writing of file outputfile2.txt is completely independent from the execution of the reading of myText.txt. As the function readFile is an asynchronous one, it will not stop the execution of any other code and will quietly keep executing in the background not blocking anything. It is to note that the only code that is waiting to be executed is the one in it’s callback and that is because we need the value of inputText to be set before writing it to outputfile.txt.
In this piece of code if you console log the value of inputText just above the second writeFile, you’ll see it is null. Why ? Because we haven’t waited for the reading to be completed and have directly entered the next line of code.

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...