Sync and async approach
The synchronous approach requires waiting for every operation to complete before executing the next one. They are called blocking functions because they block the following command from its execution until the result from all the previous commands is achieved.
On the other hand, the asynchronous approach does not wait for operations to complete and executes all the commands in the first go. Thus, they are called non-blocking functions. For every operation, the result is handled whenever it is available. This means that the previous commands run in the background while the following command is executed.

Source
The file module system works efficiently with both synchronous and asynchronous actions, making it ideal for use in both situations. We will learn how the fs handles both these actions equally well and what makes them worthy of learning. One such example is the closing of files, an async function requiring smooth functioning of the file system, and there are several such operations that need to be taken care of in the same way.
Let's have a look at the basic operations that the file system module can do:
Opening a file, reading, and writing
We could either use fs.open() to open, read or write files; fs.readFile() just to read, or fs.writeFile() to write to the file. Before using fs.open() to create a file, we need to load the fs class module to access the file system, only then we'll be able to do such operations.
fs.open() has the following syntax:
fs.open(path, flag, mode (optional), callback)

You can also try this code with Online Javascript Compiler
Run Code
fs.readFile() has the syntax:
fs.readFile(path, callback)

You can also try this code with Online Javascript Compiler
Run Code
- The path is either the file name or the entire path to it.
- The flags dictate the behaviour of the files we are opening. Some of the flags are r, r+, w, w+, a, rs, wx, ax, etc.
- Mode, if not specified, is assumed to be readwrite, or we could choose to set it to just re-read or w-write.
- As we learned earlier, callback functions are called after reading the file. They contain two arguments for errors and the data of the file, respectively.
Let’s see some examples for open(), readFile(), and writeFile():
var fs = require("fs");
console.log(“Opening file”);
fs.open('demo.txt', 'r+', function(err, data)
{
console.log(“File opened!”);
}
);

You can also try this code with Online Javascript Compiler
Run Code
Output:
Opening file
File opened!
We will create a file demo.html with the info: Hey Ninjas!
Next, we will create a javascript file with the main code:
var fs = require('fs');
fs.readFile('demo.html', function(err, info)
{
if (err)
{
return console.error(err);
}
console.log("Reading: " + info.toString());
});

You can also try this code with Online Javascript Compiler
Run Code
Output:
Reading: Hey Ninjas!
Creating or updating files
fs.writeFile() is either used to open files, or create/update them. fs.writeFile() replaces already existing files by default and in fact, asynchronously overwrites them.
The syntax for writing files is as follows:
fs.writeFile(path, data, options, callback)

You can also try this code with Online Javascript Compiler
Run Code
where “options” is an optional parameter specifying the encoding, the mode or the flag.
Below is an example of the writeFile() method:
// Import the file system module
var fs = require("fs");
fs.writeFile('input.txt', 'Hello', function(err)
{
if (err)
{
return console.error(err);
}
console.log("Written in the existing file successfully!");
console.log("New data:");
fs.readFile('input.txt', function (err, data)
{
if (err)
{
return console.error(err);
}
console.log(data.toString());
});
});

You can also try this code with Online Javascript Compiler
Run Code
Output:
Written in the existing file successfully!
New data:
Hello

The fs.appendFile() method, the writeFile() method, is synchronous in nature and appends the specified content to a file. In case we are using the append method and the file to be appended does not already exist, a new file is created by default.
The syntax for append is:
fs.appendFile(filepath, data, options, callback);

You can also try this code with Online Javascript Compiler
Run Code
where “options” is an optional parameter specifying the encoding, the mode, or the flag.
var fs = require('fs');
var data = "\n Node js coders";
fs.appendFile('input.txt', data, 'utf8', function(err)
{
if (err) throw err;
// If there is no error
console.log("Data appended!")
});

You can also try this code with Online Javascript Compiler
Run Code
or
var fs = require('fs');
fs.appendFile('input.txt', '\n Node js coders', function (err)
{
//if there is no error
console.log('Data appended!');
});

You can also try this code with Online Javascript Compiler
Run Code
Output:


Closing files
The method used for closing files is fs.close(). Closing files is an asynchronous task, and the syntax for it is:
fs.close(fd, callback)

You can also try this code with Online Javascript Compiler
Run Code
where fd is an integer denoting the file descriptor, which closes and clears the associated file.
fs.close(fd, function(err)
{
if (err)
{
console.log(err);
}
console.log("The file has been closed.");
}

You can also try this code with Online Javascript Compiler
Run Code
Output:
The file has been closed.
Deleting files
The fs.unlink() method deletes files with the File System module.
For example, if we want to delete "myfile.txt":
var fs = require('fs');
fs.unlink('input.txt', function (err)
{
if (err) throw err;
console.log('File deleted successfully!');
});

You can also try this code with Online Javascript Compiler
Run Code
Output:
File deleted successfully!

However, the fs.unlink() function won’t work on directories, which is why we use fs.rmdir() in cases when we want to remove a directory.
Now that we have understood the basics of the file system module, let us now discuss some faqs based on the above discussion.
Frequently Asked Questions
Q1. Why is Node.js used?
Ans. Node.js can be used in frontend and backend, and mainly for non-blocking and event-driven servers. It’s used for traditional websites and also backend API services.
Q2. Can we rename an existing file in Node JS?
Ans. Yes, we can rename files in Node JS using the fs.rename() method. Its syntax is as follows: fs.rename('originalname.txt', 'newname.txt', callback).
Q3. What is a process in node?
Ans. The process in Node JS is a global object that can be accessed from anywhere. Node. js lets users get all process information such as process id, platform, version, release, CPU usage, etc. It also provides the option to kill the process, set groups, unmask, etc.
Q4. What is blocking and non-blocking I/O?
Ans. Blocking IO requires the I/O to be completed and received before proceeding with anything next in the thread. However, in non-blocking I/O, requests are queued right away and the functions are returned while the I/O can conveniently be processed later.
Key takeaways
We learned about Node JS, the file system module, and its various functions in which we’ve discussed methods to open, create, read, write, append, update, rename and delete files.
The discussion is not over yet, there is much more to explore in the file system module. Ninja, it's your turn now to play with the files, and don’t forget to implement the above-stated methods for more clarity.
Check out this article - File System Vs DBMS
You can go to Coding Ninjas Studio to try and solve more problems for practice. Share this blog with your friends if you found it helpful! Until then, All the best for your future endeavours, and Keep Coding.