Node.js fs.read() Method

08 Oct, 2021
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 fs package reads the file using a file descriptor. In order to read files without file descriptor the readFile() method of 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 at.
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 position is null, data is read from the current file position.
callback: The callback function accepts the three arguments ie. (err, bytesRead, buffer).
Explanation: 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 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:
var fs = require("fs");var 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 consolevar readline = require('readline-sync');var fs = require("fs");  var 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

Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
JWT Authentication with Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React