The Wayback Machine - https://web.archive.org/web/20240630063850/https://www.geeksforgeeks.org/node-js-fs-read-method/
Open In App

Node.js fs.read() Method

Last Updated : 31 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Node.js is used for server-side scripting. Reading and writing files are the two most important operations that are performed in any application. Node.js offers a wide range of inbuilt functionalities to perform read and write operations. The fs package contains the functions required for file operations. The read() method of the fs package reads the file using a file descriptor. In order to read files without file descriptors the readFile() method of the fs package can be used. 

Syntax

fs.read(fd, buffer, offset, length, position, callback)

Parameters:

  • fd: File descriptor returned by fs.open() method.
  • buffer: Stores the data fetched from the file.
  • offset: Offset in the buffer indicating where to start writing.
  • length: An integer that specifies the number of bytes to read.
  • position: An integer that specifies where to begin reading from in the file. If the position is null, data is read from the current file position.
  • callback: The callback function accepts the three arguments ie. (err, bytesRead, buffer).
    • err: An Error object is provided if an error occurs during the read operation. Otherwise, it is null.
    • bytesRead: The number of bytes read from the file.
    • buffer: The buffer object passed to the method, filled with the data read from the file.

The fs.open() method opens the file and returns a file descriptor. A file descriptor is a number or index that is stored in the file descriptor table by the kernel and is used to uniquely identify an open file in the computer’s operating system. The fs.read() method reads the file using the file descriptor and stores it in the buffer. The contents of the buffer are printed out as output. The fs.close() method is used to close the file. 

Example 1: In this example, we will use fs.read() method

javascript
const fs = require("fs");
const buffer = new Buffer.alloc(1024);

console.log("Open existing file");
fs.open('gfg.txt', 'r+', function (err, fd) {
    if (err) {
        return console.error(err);
    }

    console.log("Reading the file");

    fs.read(fd, buffer, 0, buffer.length,
        0, function (err, bytes) {
            if (err) {
                console.log(err);
            }

            if (bytes > 0) {
                console.log(buffer.
                    slice(0, bytes).toString());
            }
            console.log(bytes + " bytes read");

            // Close the opened file.
            fs.close(fd, function (err) {
                if (err) {
                    console.log(err);
                }

                console.log("File closed successfully");
            });
        });
});

Output:

Open existing file
Reading the file
0 bytes read
File closed successfully

Example 2: Taking dynamic input for file name/path. 

javascript
// Module required to accept user
// input from console
const readline = require('readline-sync');
const fs = require("fs");

let path = readline.question("Enter file path: ");
console.log("Entered path : " + path);

console.log("File Content ");

fs.stat(path, function (error, stats) {

    // 'r' specifies read mode
    fs.open(path, "r", function (error, fd) {
        var buffer = new Buffer.alloc(stats.size);
        fs.read(fd, buffer, 0, buffer.length,
            null, function (error, bytesRead, buffer) {
                var data = buffer.toString("utf8");
                console.log(data);
            });
    });
});

Output:

C:\Users\User\Desktop>node read3.js
Enter file path: new.txt
Entered path : new.txt
File Content
Hello World..
Welcome to GeeksForGeeks..
This is a Node.js program


Previous Article
Next Article

Similar Reads

Create a Read More Read Less Button using HTML CSS and JavaScript
The "read more - read less" button is a commonly used feature that enhances user experience by providing a convenient way to reveal or hide content. The article covers two distinct approaches, including Display Inline and Display Block. Table of Content Using Display InlineUsing Display BlockUsing Display InlineCreate a separate HTML, CSS, and Java
4 min read
Node.js Stream readable.read() Method
The readable.read() method is an inbuilt application programming interface of Stream module which is used to read the data out of the internal buffer. It returns data as a buffer object if no encoding is being specified or if the stream is working in object mode. Syntax: readable.read( size ) Parameters: This method accepts single parameter size wh
2 min read
Node.js filehandle.read() Method
The filehandle.read() method reads the file using a file descriptor. In order to read files without file descriptors the readFile() method of the filehandle package can be used. Node.js is used for server-side scripting. Reading and writing files are the two most important operations that are performed in any application. Node.js offers a wide rang
2 min read
Node.js fs.Dir.read() Method
The fs.Dir.read() method is an inbuilt application programming interface of class fs.Dir within File System module which is used to read each next directory (dirent) one by one asynchronously. Syntax: const fs.Dir.read(callback) Parameter: This method takes a callback function as a parameter that has the following arguments. err: if any error occur
2 min read
Node.js REPL (READ, EVAL, PRINT, LOOP)
Node.js is an open source server-side Javascript run-time environment built on Chrome's JavaScript Engine(V8). Node.js is used for building fast and scalable applications and is an event driven, non-blocking I/O model. REPL (READ, EVAL, PRINT, LOOP) is a computer environment similar to Shell (Unix/Linux) and command prompt. Node comes with the REPL
2 min read
How to read and write Excel file in Node.js ?
Node.js is an open-source and cross-platform JavaScript runtime environment that can also be used to read from a file and write to a file which can be in txt, ods, xlsx, docx, etc format. The following example covers how an excel file(.xlsx) file is read from an excel file and then converted into JSON and also to write to it. It can be achieved usi
3 min read
How to read command line arguments in Node ?
Command-line arguments (CLI) consist of text strings utilized to provide extra information to a program during its execution via the command line interface of an operating system. Node facilitates the retrieval of these arguments through the global object, specifically the process object. Below are the examples that give a better understanding: Exa
2 min read
How to read and write files in Node JS ?
NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metadata. Let's explore how to read and write files in N
2 min read
How to Read a File Line by Line using Node.js ?
The ability to Read a File Line by Line using Node allows us to read large files without entirely storing them in memory. It is useful in saving resources and improving the efficiency of the application. It allows us to look for the information that is required and once the relevant information is found, we can stop the search process and can preve
3 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and text-based format for exchanging data between diff
3 min read
three90RightbarBannerImg