Working with fs Module in Node Js

Learn via video courses

Overview

The file system or fs module in node js is one of the core modules provided by Node.js, which provides us with the functionality to interact with and access the file system. This module helps us in reading, writing, and updating the file as well as other streams in node js. The fs module in node js is very helpful in performing all file Input / Output operations asynchronously as well as synchronously.

Pre-requisites

The file system or the fs module in node js supplies a lot of helpful functionality to access and interact with the file system. Being a part of the core modules of Node.js, the fs (file system ) module does not require installation from any external provider or through Node Package Manager (npm) We can simply use all the methods and functionalities provided by the fs module just by requiring it.

Before ES6 syntax :

ES6 syntax :

The file system or the fs module in node js provides us with an Application Programming Interface (API) to interact with and access the File System of the operating system (Server).

Introduction to File System or fs Module in Nodejs

The file system or the fs module in node js enables us to interact and work with the file system, which is one of the fundamental tasks when writing a piece of code. To handle file operations like reading, updating and deleting, etc., Node.js provides us with the functionality of file Input and Output by providing wrappers around the standard POSIX Library functions. Each of those available methods in the fs module in node js is available in two versions, namely the (default) asynchronous version and the synchronous version.

Many developers think that working with a file is all about reading and writing to the file. In contrast, those two operations are the most commonly used; a lot more lies under the hood. The next topic will go into the details of those methods when working with the file system.

Usage for File System or the fs Module in Nodejs

Now we will discuss about the common usage of methods provided by the fs module in node js.

Read Files

You can create a file with the fs.read() function or fs.readFile() to read files in an asynchronous manner or readFile Sync to read files in a synchronous manner.

Following is the syntax of fs.read() methods provided by the fs module in node js, to read from a specified file :

This method will use an (fd) file descriptor to read the file. In case, you want to read the file directly using the file name using other methods provided by the fs module in node js.

Description of the Parameters :

  • fd − It is the file descriptor returned by fs.open().
  • buffer − It is the buffer that the data will be written to.
  • offset − It is the offset in the buffer to start writing at.
  • length − It is an integer specifying the number of bytes to read.
  • position − It is used to specify the position where to begin reading the file. If the position is empty, data will be read from the current file position.
  • callback − It is the callback function that gets the three arguments (err, bytesRead, buffer).

Let us create a javascript file named index.js with the following code:-

Now run the index.js to see the result −

Output :-

Method to read file asynchronously:-

Output:

Method to read file synchronously:-

Output:

Create Files

There are three methods that can be used to create files and are provided by the fs module in node js.

  1. fs.open() is used to create, open, and write files;
  2. fs.appendFile() is used to create and populate a file;
  3. fs.writeFile() is used to create and write files.

The program code below will create a file with the name mynewfile1.txt with the contents Hello Friends, Happy Coding! using the fs.appendFile().

Following is the syntax to create from a file using fs.open():−

Description of the Parameters :

  • path : <string> | <Buffer> | <URL> It is a String that specifies the file path.
  • flags : <string> | <number> See support of file system flags. Default: 'r'.
  • mode : <string> | <integer> Default: 0o666 (readable and writable)
  • callback : This function is to be executed when the file is opened.
  • err : This is the error that would be thrown if the method fails.
  • fd : <integer> It acts as a reference to the original file.

Now we will create a new file with the name mynewfile2.txt using fs.open().

In the above code example, the w (write) flag is used to tell the fs.open() function that you want to create or write to a new file. This function will create an empty file if there is no file with the appointed name. Regardless, if the file already lives, the fs.open() function will override it.

The fs.writeFile(): is used to replace the file and its content if the file is found. If the file is not found, a new file will be created with the specified content.

Update Files

The File System or the fs module in node js has these two methods for updating files:

  • fs.writeFile()
  • fs.appendFile()

The fs module in node js provides the fs.appendFile() is used to append the specified content at the end of the selected file.

Syntax :

Description of the parameters :

  • path : <string> | <Buffer> | <URL> | <number> filename or file descriptor.
  • data : <string> | <Buffer> The data to be written in the file.
  • options : <Object> | <string>
  • encoding : <string> | <null> Default: 'utf8'
  • mode : <integer> Default: 0o666
  • flag : <string> See support of file system flags. Default: 'a'.
  • callback : <Function> The function to be executed when the file is opened.
  • err : <Error> It is an error that would be thrown if the method fails.

Now let us open the file mynewfile1.txt and append This is my text. at its end.

Example:

The fs module in node js provides fs.writeFile() method is used to replace the specified file and its content:

Syntax:

Description of the parameters :

  • file : <string> | <Buffer> | <URL> | <number> filename or file descriptor.
  • data : ``||||` The data to be written in the file.
  • options : <Object> | <string>
  • encoding : <string> | <null> Default: 'utf8'
  • mode : <integer> Default: 0o666
  • flag : <string> See support of file system flags. Default: 'w'.
  • signal : <AbortSignal> allows aborting an in-progress writeFile
  • callback : <Function> The function is to be executed when the file is opened.
  • err : <Error> | <AggregateError> It is an error that would be thrown if the method fails.
  • Now let us write the data Hello world! to the file mynewfile2.txt.

    Example:

    Delete Files

    The file system or fs module in the node js module has an unlink() function to delete files.

    Syntax :

    Description of the parameters:

    • path : <string> | <Buffer> | <URL> The name of the file to be deleted.
    • callback : <Function> The function is to be executed when the file is deleted.
    • err : <Error> It is an error that would be thrown if the method fails.

    Let us assume there is a file with the name mynewfile1.txt, let's delete it.

    Example:

    Rename Files

    File System or the fs module in node js provides us with the fs.rename() method to rename a file in your system.

    Syntax :

    Description of the parameters :

    • oldPath : <string> | <Buffer> | <URL> Old filename which is to be replaced.
    • newPath : <string> | <Buffer> | <URL> New filename
    • callback : <Function> Function to be executed when the name is changed.
    • err : <Error> It is an error that would be thrown if the method fails.

    Let's change the name of mynewfile1 to myrenamedfile.

    Example:

    In the case that newPath already exists, then that file will be overwritten.

    List of flags used in all of the above File Operations provided by the fs module in node js:

    • r - If the file is already in the system, this flag opens the specified file for reading; otherwise, gives an error.
    • r+ - If the file is already in the system, this flag opens the specified file for reading and writing; otherwise, gives an error.
    • rs - opens the file to be read in synchronous mode.
    • rs+ - opens a file for both readings and writing in synchronous mode.
    • w - Opens a file for writing.
    • wx - same as w, but gives an error if the file already exists.
    • w+ - opens a file for both writing and reading.
    • wx+ - same as w+, but gives an error if the file already exists.
    • a - opens the file for appending.
    • ax - same as a but gives an error if the file already exists.
    • a+ - opens a file for appending and reading, and creates a new file in case of not found.
    • ax+ - is the same as a+ gives error if the file already exists.

    Revolutionize Your Node JS Exploration! Immerse Yourself in Our Full Stack Web Developer Course, Crafted by Industry Visionaries. Enroll Now!

    Synchronous and Asynchronous Methods

    What is Synchronous and Asynchronous Approach?

    As we have discussed, the various uses of the file system or the fs module in node js. All the functions provided by the fs module have both synchronous and asynchronous forms. In synchronous methods, the program execution stands blocked while the file operation is being performed. Hence they are also known as blocking functions. On the contrary, the asynchronous functions do not block the program execution. All the statements are executed one after the other, but a statement will get executed even if the previous statement has not finished executing. Hence asynchronous methods are also called non-blocking methods.

    synchronous-asynchronous-approach-in-nodejs

    Synchronous methods introduction by fs module in node js:

    They block the program execution while the file operation is being performed. Hence they are known as blocking functions. They require the path of the file or file descriptor as the argument. The synchronous methods should be used in case of lightweight operations like fetching a small amount of data.

    Syntax :

    Example:

    We can also make use of the path of the file. The following code shows this:

    Asynchronous methods introduction by fs module in node js:

    Asynchronous functions do not block the program execution while they are getting executed. Hence they are called non-blocking functions. In the asynchronous method of execution, a statement will execute even if the previous statement has not produced an output. In addition to the parameters of synchronous functions, the asynchronous functions have a callback function with two parameters, error and fd.

    They are preferred over synchronous functions as they do not block program execution. We should use these methods if the operation is time-taking and the user can be shown the progress of the operation with the help of percentages etc.

    Syntax:

    Example:

    List of Methods Provided by (file system) or the fs Module in Nodejs

    MethodDescription
    fs.access()Used to check if a file exists or to test permissions related to the file.
    fs.chmod()Used to change permissions of a file.
    fs.appendFile()It appends data to a file or creates a new file if the specified file doesn't exist.
    fs.close()Used to close file descriptor
    fs.close()Opens a file and returns the file descriptor.
    fs.copyFile()Copy a file.
    fs.chown()Change the owner of the file.
    fs.createReadStream()Create a readable file stream
    fs.createWriteStream()Create a writable file stream
    fs.link()Creates a hard link to a given path. The link works even when the file is renamed.
    fs.mkdir()Creates a new directory.
    fs.rmdir()Delete a directory.
    fs.mkdtemp()Creates a temporary directory
    fs.readdir()Read directory contents.
    fs.readFile()Read file contents.
    fs.writeFile()Write to a file.
    fs.rename()Rename file/folder.
    fs.symlink()Create a symbolic link to a file.
    fs.readlink()Read symbolic link’s value.
    fs.unlink()Remove a symbolic link.
    fs.watchFile()Monitor a file for changes.
    fs.unwatchFile()Stop watching a file for changes.
    fs.stat()Returns an object that contains several properties and methods to get file details.
    fs.realpath()It resolves a relative file path to the full path.
    fs.truncate()Truncate a file to a specified length.
    fs.utimes()Change the timestamp of a file.

    Example of Synchronous File Operation

    Let’s try appending data to a file with the help of synchronous operations.

    • Create a file with some data in it.
    • We will read the file to print the initial contents and then append data to it.

    Example:

    Let's suppose there is a file test.txt in your system which contains This is the content of the test file.

    Output:

    As you know, the final contents of the file have Added new data in the test file. in the end.

    Example of Asynchronous File Operation

    In the following code, we are first reading file contents. Then appending data to the file asynchronously. In case of any error, the error message will be shown; otherwise, the final contents will be shown.

    Example:

    Output:

    Difference between Synchronous and Asynchronous by fs module in node js in brief:

    SynchronousAsynchronous
    Synchronous functions provided by the fs module in node js block the program execution while the file operation is being performed.Asynchronous functions provided by the fs module in node js do not block the program execution while the file operation is being performed.
    They are known as blocking functions.They are known as non-blocking functions.
    They have path of the file/ file descriptor and options object as arguments.They have path of the file/ file descriptor, options object, and a callback function as arguments.
    Eg - readFileSync(), renameSync(), writeSync().Eg - readFile(), rename(), write().

    Want to become a back-end superstar? Scaler Topics Node.js course will guide you towards becoming a skilled server-side developer.

    Conclusion

    • The file system or the fs module in node js is one of the core modules provided by Node.js, which helps in accessing and interacting with the file system and other streams in Node.js.
    • The file system or the fs module in nodejs helps in performing all file system operations both synchronously and asynchronously.
    • Other than reading, and writing there are a lot more functions like append (adding at the end of file), chmod(permission change), mkdir(create directory), etc.
    • All the functions provided by the fs module in node js are available in both synchronous and asynchronous forms, the second one being the default.
    • The execution of the program is blocked by the synchronous functions while file operation is being performed. Hence they are called blocking functions. Eg - readFileSync().
    • The asynchronous functions do not block the execution of the program while file operation is being performed. Hence they are called non-blocking functions. Eg - readFile().
    • Synchronous functions have file path / descriptor and options object as parameters. The asynchronous functions have an extra parameter of the callback function.
    • There is a numerous variety of flags like r, r+ etc are used for different types of file operations. They are specified in the options object.