Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Node.js filehandle.read() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 range of inbuilt functionalities to perform read and write operations. The fs package contains the functions required for file operations.

Syntax:

filehandle.read( buffer, offset, length, position );

Parameters: This function accepts four parameters as mentioned above and described below:

  • buffer: Stores the data fetched from the file. It is the buffer in which the data will be written.
  • 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. The position is an argument specifying where to begin reading from in the file. If the position is null, data is read from the current file position.

Return value: It returns the Promise.

Note: “GFG.txt” should be present in the directory with the following text:

GeeksforGeeks - A computer science portal for geeks

Example: In this example, we will see the use of filehandle.read() method

javascript




// Node.js program to demonstrate the
// Node.js filehandle.read() Method
 
// Import the filesystem module
const fs = require('fs');
const fsPromises = fs.promises;
 
let buffer = new Buffer.alloc(1024);
 
console.log(fs.readFileSync('GFG.txt', 'utf8'));
 
// Using the async function to
// ReadFile using filehandle
async function doRead() {
    let filehandle = null;
 
    try {
        // Using the filehandle method
        filehandle = await fsPromises
            .open('GFG.txt', 'r+');
 
        // Calling the filehandle.read() method
        await filehandle.read(buffer,
            0, buffer.length, 0);
    } finally {
        if (filehandle) {
 
            // Close the file if it is opened.
            await filehandle.close();
        }
    }
}
 
doRead().catch(console.error);

Run the app.js file using the following command:

node app.js

Output:

GeeksforGeeks - A computer science portal for geeks
My Personal Notes arrow_drop_up
Last Updated : 06 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials