Friday, January 24, 2025
HomeProgrammingNode JS fs.readFile() Method

Node JS fs.readFile() Method

The fs.readFile() method in Node.js is part of the fs (File System) module and is used to asynchronously read the contents of a file.

Here is a basic syntax:

const fs = require('fs');

fs.readFile(path, options, (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  // The file content is in the `data` argument
  console.log('File content:', data.toString()); // converting buffer to string
});

Parameters:

  1. path (string | Buffer | URL): The path to the file you want to read.
  2. options (optional):
    • encoding (string | null): The character encoding to use (e.g., 'utf8'). If not provided, it will return a Buffer.
    • flag (string): A string flag to specify the behavior (e.g., 'r' for reading).
  3. callback: A callback function that takes two arguments:
    • err: An error object (if an error occurs).
    • data: The content of the file (as a Buffer or a string depending on the encoding).
See also  Difference between Operating system and Application

Example with Encoding:

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File content:', data);
});

Important Points:

  • The method is asynchronous, so it does not block the execution of the program while the file is being read.
  • The callback is executed once the file reading operation is complete, passing the file content (or error if something went wrong).
  • If no encoding is specified, the result will be a Buffer, which you can convert to a string (using .toString()).
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x