Open In App

Node.js fs.read() Method

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:

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




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. 




// 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

Article Tags :