Accessing File System and Understanding Asynchronous and Synchronous Programming in Node.js

In this article you will learn how to Access File System and understand Asynchronous and synchronous programming in node.js.

Accessing the file system is a very common task but not with JavaScript since it was meant to run in a browser. Although HTML 5 comes with a file system API, it's not fully supported by every browser yet. But node.js gives a full support for accessing the file system and it comes with the node.js installation.

Understanding the File System and its capabilities

Node.js installation comes with a module called "fs" that acts as a wrapper for multiple file operations. This provide various methods for the standard file operations. We will use the read, write and watch methods that are most popular in both asynchronous and synchronous mode. To learn about all the methods go to the official documentation of the file system API here.

Reading from a file asynchronously

As we know, by default every function in node.js is treated as an async function, so we do not need to specify async anywhere in order to do the async programming.

Now, in our example we created a file with sample text and named it Readme.txt, now we will read that file.

Let's create a JavaScript file with the following code:

var fs = require("fs");
console.log("Starting");
fs.readFile("Readme.txt","UTF-8", function(error,data) {
console.log(data);
});
console.log("Finished");

Now save this file as ReadFile.js. You can give it any name you want. In this example I included a fs module for the file system, then I am using the console.log to print out the message and the function fs.readFile reads the file asynchronously. It takes three arguments, the first is the name of the file with the path details. I am keeping this file in the root so I don't need to provide the full path. If you are reading a file from another directory then don't forget to specify the full path details. The second argument is the "encoding format" of the file and the third and most important is the callback function that will give the data upon success or that throws an error upon failure. Let us run this file now in order to understand the concept.

To run the file, open the node.js command prompt from the programs and type node ReadFile.js and press Enter.

Node1.jpg

In order to understand the concept of asynchronous programming, look at the output of the file. The first console.log is printed, then the third console.log is printed instead of the data from the file since the function is reading the content of the file in the background and the flow of control had moved to the next statement and executed it, then the callback of the function; it completes reading the file and displays the content of the file.

Reading the content of the file synchronously

As we saw, the flow of control moves to the next statement and executes all the statements until it gets a callback from the function, but sometimes we don't need that; we need a traditional line by line execution of the statements in the same manner that they exist in the source code, so for that we have a synchronous method. We just need to use the method readFileSync() that takes the "filename" and the encoding as the argument and we don't have the callback function here, instead we store the result in a variable "data".

Create a new js file with the name ReadFileSync.js and write the following code:

var fs = require("fs");
console.log("starting");
var data = fs.readFileSync("Readme.txt","UTF-8");
console.log(data);
console.log("Finished");

Now go to the node.js command prompt and type node ReadFileSync.js in order to run the file.

Node2.jpg

Now you can clearly see the difference between the output of the async and sync functions, in sync the statements are executed line by line and it does not move to the next statement until the current statement is executed.

Writing into a file asynchronously

Writing into a file is pretty similar to reading a file; the only difference is we need to use the writeFile function that takes as the first parameter the filename and the second is the content of the file.

create a new file WriteFile.js and type the following code:

var fs = require("fs");
console.log("Starting to write");
fs.writeFile("Readme.txt","Adding to the file", function(error,data) {
console.log("Writing in file completed");
});

Now run it using the node.js command prompt and type node WriteFile.js.

Node3.jpg

Writing into a file synchronously


Now similarly we need to use a writeFileSync function that works similarly as the readFileSync function, it takes the "filename" and the content of the file as the argument.

Create a new js file WriteFileSync and write the following code.

var fs = require("fs");
console.log("starting");
var data = fs.writeFileSync("Readme.txt","Added a new data");
console.log("Finished");
Run it and check out the output.

Watching a File

This is one of the most interesting modules of the file system, it allows programs to watch for modifications to specific files.

Create a new js file WatchFile.js and write the following code:

var fs = require("fs");
var fileName = "Readme.txt");
fs.watch(fileName,{
persistent:true},
function(event,filename){
console.log(event +,"occurred on" ,filename);
});

Here Watch takes three argument;, filename, persistent (a Boolean variable that is by default True and if True then it prevents the program from terminating) and a call back function that is triggered whenever there is a modification to a file. It can be useful when multiple people are working on the same file and if anyone updates the file then we can write code to update the entire file.

Conclusion

We tried to understand the difference between asynchronous and synchronous programming by using the File System and we learned about the various file system functions, there are about 50 functions and we only discussed the most used functions such as read, write and watch. To learn about more functions, please visit here.

Please provide feedback.