Explain about Read and Write of a file using JavaScript

Handling file operations such as reading and writing is a common requirement in many JavaScript applications, especially on the server side using Node.js. This article explains how to perform these operations using Node.js’s built-in fs (File System) module.

The fs Module

The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. It can be used to perform operations such as reading, writing, updating, and deleting files.

The fs.readFile() and rs.writeFile() methods are used to read and write of a file using javascript.

fs.readFile()

The file is read using the fs.readFile() function, which is an inbuilt method. This technique reads the full file into memory and stores it in a buffer. 

Syntax:

fs.readFile( file_name, encoding, callback_function )

Parameters:

  • filename: It contains the filename to be read, or the whole path if the file is saved elsewhere.
  • encoding: It stores the file’s encoding. ‘utf8’ is the default setting.
  • callback function: This is a function that is invoked after the file has been read. It requires two inputs:
  • err: If there was an error.
  • data: The file’s content.
  • Return Value: It returns the contents contained in the file, as well as any errors that may have occurred.

fs.writeFile()

The fs.writeFile() function is used to write data to a file in an asynchronous manner. If the file already exists, it will be replaced.

Syntax:

fs.writeFile( file_name, data, options, callback )

Parameters:

  • file_name: It’s a string, a buffer, a URL, or a file description integer that specifies the location of the file to be written. When you use a file descriptor, it will function similarly to the fs. write() method.
  • data: The data that will be sent to the file is a string, Buffer, TypedArray, or DataView.
  • options: It’s a string or object that may be used to indicate optional output options. It includes three more parameters that may be selected.
  • encoding: It’s a string value that indicates the file’s encoding. ‘utf8’ is the default setting.
  • mode: The file mode is specified by an integer number called mode. 0o666 is the default value.
  • flag: This is a string that indicates the file-writing flag. ‘w’ is the default value.
  • callback: This function gets invoked when the method is run.
  • err: If the process fails, this is the error that will be thrown.

Let’s understand how to write and read files using an example, In the below example, we are creating a file using the writeFile() method and reading the content of the file readFile() method.

Project Structure:

Example: Implementation to Read and Write of a file using JavaScript.

index.js
const fs = require("fs");
console.log(" Writing into an file ");

// Sample.txt is an empty file
fs.writeFile(
    "sample.txt",
    "Let's write a few sentences in the file",
    function (err) {
        if (err) {
            return console.error(err);
        }

        // If no error the remaining code executes
        console.log(" Finished writing ");
        console.log("Reading the data that's written");

        // Reading the file
        fs.readFile("sample.txt", function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Data read : " + data.toString());

        });
    }
);

Output:

Conclusion

The fs module in Node.js provides robust methods for file operations, allowing developers to read, write, append, and delete files both synchronously and asynchronously. While synchronous methods are simpler to understand and use, asynchronous methods are more efficient and should be preferred in most scenarios to prevent blocking the event loop. By utilizing these file operations, you can build more dynamic and responsive Node.js applications.


Contact Us