What is Nodejs File System?

Konfinity
March 8,2021 - 8 min read
 What is Nodejs file system?

Modules in Nodejs are very similar to libraries, it is a group of functions that are included in a Nodejs application. Modules are reused throughout the application and do not interfere with other modules. Each of them has their own context and are placed in separate Javascript files inside separate folders. In Nodejs, there are three types of modules. The three type of modules are core, local and third part modules.

In this blog, we are going to talk about the Nodejs file system module. There is a file system module in Nodejs that implements file input output using simple wrappers around standard POSIX functions. This module basically allows you to work with file systems on your computer. This module enables developers to work with the file system on its computers. The require () method includes the File System module. This module is used to create, read, update, delete, rename or read files. For example, the function fs.readFile() is used to read existing files on the computer. There are also a bunch of methods used for creating new files are fs.appendFile (), fs.open (), fs.writeFile().

The first method is used to, as the name suggests, append the given file. Also, if one particular file is appended but does not exist then a file of the same name will be created. The syntax of fs.appendFile () would look something like -

  • fs.appendFile('newfile.txt', 'Web development at Konfinity!’, function (err) {
  • if (err) throw err;
  • console.log (Successful!');
  • });

The next method is the fs.open() method which method takes a "flag" as the second argument. If the flag is "w", the file is opened for writing and an empty file is created if the file does not exist. The syntax of the fs.open() method looks like –

  • fs.open('konfinityfile2.txt', 'w', function (err, file) {
  • if (err) throw err;
  • console.log (Successful!');
  • });

We are going to talk about the fs.open () method in detail. The code above displays a basic syntax of this method, let’s dwell deep into the parameters used in this method. The syntax of the method is - fs.open(path, flags[, mode], callback). The parameters used are path, flags, mode and call back.

The path signifies the string which is the file name, flags refer to the behaviour of the particular file to be opened. We will explain the possible values of a flag in this blog itself.

The next parameters are mode and call back. Mode sets the file mode if the file is created, the default value is readable and writeable. The callback function has two arguments (err, fd).

There are various values for the parameter flags that we mentioned earlier. The various flags are used for read and write operations. There is. The flag ‘r’ is used for opening a file for reading; however, an exception occurs if the file doesn’t exist. There is another flag, ‘r+’ which opens a file for reading as well as writing and in this flag also, an exception occurs if the file doesn’t exist.

A flag, ‘rs’ opens a file for reading in synchronous mode and similarly ‘rs+’ opens a file for reading and writing in synchronous mode. There is another flag, ‘w’, that, as the name suggests, opens a file for editing or writing. In this flag, a new file is created if it doesn’t already exist and is truncated if it exists. The ‘wx’ flag is similar but the only difference is that it fails if the path exists. There is a ‘w+’ flag which opens a file for reading as well as writing and also if a file does not exist, a new file is created or is truncated if it exists already. There is a flag ‘wx+’ which is similar to ‘wx’ but the only difference is that it fails if the path exists.

Another set of flags used are a, a+ and ax. The first flag, ‘a’, is used for opening a file for appending and creates one if one doesn’t exist already. Next, ‘ax’, is very similar to ‘a’ with the only difference being that it fails if the path doesn’t exist. The next set of flags are ‘a+’ and ‘ax+’. The only difference between the two is ‘ax+’ fails if path doesn’t exist. These flags are used to open a file for reading and appending.

Exploring Methods

The fs.writeFile() method is used if a particular file is to be replaced. Also, a new one will be created, if the file doesn’t already exist,.

  • fs.writeFile('konfinityfile3.txt', 'Web development at Konfinity!’, function (err) {
  • if (err) throw err;
  • console.log (Successful!');
  • });

Apart from these methods, there are a couple of other methods included in the Nodejs file system module too. Let’s understand the concept in detail. The methods generally used to update files in a system are fs.appendFile() and fs.writeFile().

fs.appendFile() is a method that adds or inserts particular content at the end of the file mentioned in the code. The syntax for the method is–

  • fs.appendFile('Konfinityfile1.txt', ' Successful career in technology', function (err) {
  • if (err) throw err;
  • console.logv('Append Successful!');
  • });

This code would append the text " Successful career in technology " to the end of the file that goes by the name "Konfinityfile1.txt".

The fs.writeFile() method replaces the file and content mentioned in the code. The syntax of fs.writeFile() is

  • fs.writeFile('mynewfile3.txt', 'Web development', function (err) {
  • if (err) throw err;
  • console.log('Successful!');
  • });

This code replaces the content of one particular file.

There are methods in the file system module used to delete files. fs.unlink() method is used to delete a particular file. The syntax of this method is –

  • fs.unlink('KonfinityExample.txt', function (err) {
  • if (err) throw err;
  • console.log ('Deletion Successful!');
  • });

The code basically deletes the file "KonfinityExample.txt":

In Nodejs file system, developers can upload as well as rename files in their machines also. The fs.rename() method renames a file mentioned in the code, the code for the same looks like -

  • fs.rename ('Konfinity.txt', 'KonfinityRenamed.txt', function (err) {
  • if (err) throw err;
  • console.log ('The File is Renamed!');
  • });

The code above, renames the file "Konfinity.txt" to "KonfinityRenamed.txt":

One important thing to notice is that all the methods mentioned above has a prefix variable ‘fs’. Before executing any of this code, you would have to explicitly mention one particular line of code and that is - var fs = require('fs');

Now that we have understood the basic concepts of the Nodejs file system module along with the methods used within the module. In the next segment, we are going to talk about the synchronous and asynchronous forms of methods in the Nodejs file system module. Let’s get started!

Synchronous vs Asynchronous

The file system module has methods with synchronous as well as asynchronous forms. In this section, we are going to create a comparison between the synchronous and asynchronous working of some methods within the file system module.

In the asynchronous method, the last parameter is taken as the completion function call back whereas the first parameter of the call back function is taken as error. One advantage of asynchronous method over the synchronous one is that it never blocks a program during its execution. A synchronous method can block the second program during execution. Let’s understand this with an example.

The first step will be to create a text file named sampleinput.txt with the following content −

Konfinity is the best platform to learn as well as make a lucrative career in technology!

As a part of the next step, we will create a Javascript file, for example. samplemain.js with the following content -

  • var fs = require("fs");
  • fs.readFile('sampleinput.txt', function (err, data) {
  • if (err) {
  • return console.error(err); }
  • console.log ("Asynchronous way: " + data.toString());
  • });
  • var data = fs.readFileSync('sampleinput.txt'); console.log("Synchronous way: " + data.toString());
  • console.log ("Program Finish");

In the code above, we have used the method fs.readFile () in both asynchronous and synchronous methods. The next step is to run the samplemain.js file, (the code for the same is - $ node main.js)

The output of the following code is -

Synchronous read: Konfinity is the best platform to learn as well as make a lucrative career in technology! Program Ended Asynchronous read: Konfinity is the best platform to learn as well as make a lucrative career in technology!

Now that we have read enough about Synchronous and Asynchronous forms of the Nodejs file system module, we have finished our discussion on Nodejs file system modules. If you have any queries regarding the file system module in Nodejs, feel free to contact us and build a community of enthusiastic technocrats.

Out of the many available, the course that would be most suitable is Konfinity’s Web Development Course The course is well-researched and is one of the most beneficial training courses out there. It is developed by experts from IIT DELHI in collaboration with tech companies like Google, Amazon and Microsoft. It is trusted by students and graduates from IIT, DTU, NIT, Amity, DU and more.

We encourage technocrats like you to join the course to master the art of creating web applications by learning the latest technologies, right from basic HTML to advanced and dynamic websites, in just a span of a few months.

Konfinity is a great platform for launching a lucrative tech career. We will get you started by helping you get placed in a high paying job. One amazing thing about our course is that no prior coding experience is required to take up our courses. Start your free trial here.

Chat with us