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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...