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

Node JS fs.readFile() Method

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

In Node.js, the fs (File System) module furnishes a collection of methods for interacting with the file system. Among these methods, fs.readFile() stands out as a fundamental tool for reading data from files asynchronously. This article will delve into the fs.readFile() method, exploring its syntax, parameters, usage, and error handling.

Syntax:

fs.readFile( filename, encoding, callback_function )

Parameters:

The method accepts three parameters as mentioned above and described below:  

  • filename: It holds the file’s name to read or the entire path if stored at another location.
  • encoding: It holds the encoding of the file. Its default value is ‘utf8’.
  • callback_function: A callback function is called after reading the file. It takes two parameters:
    • err: If any error occurred.
    • data: Contents of the file.

Return Value:

It returns the contents/data stored in file or error if any.

Steps to Create Node JS Application

Step 1: In the first step, we will create the new folder by using the below command in the VScode terminal.

mkdir folder-name
cd folder-name

Step 2: Initialize the NPM using the below command. Using this the package.json file will be created.

npm init -y

Project Structure:

NodeProj

Project Structure

Example 1: Below examples illustrate the fs.readFile() method in Node JS. The output is undefined it means the file is null. It starts reading the file and simultaneously executes the code. The function will be called once the file has been read meanwhile the ‘readFile called’ statement is printed then the contents of the file are printed.

JavaScript
//index.js

// Node.js program to demonstrate
// the fs.readFile() method

// Include fs module
var fs = require('fs');

// Use fs.readFile() method to read the file
fs.readFile('Demo.txt', 'utf8', function (err, data) {
    // Display the file content
    console.log(data);
});

console.log('readFile called');

Step to run the Node App:

node index.js

Output: 

readFile called
undefined

Example 2: Below examples illustrate the fs.readFile() method in Node JS:

javascript
//index.js

// Node.js program to demonstrate
// the fs.readFile() method

// Include fs module
var fs = require('fs');

// Use fs.readFile() method to read the file
fs.readFile('demo.txt', (err, data) => {
    console.log(data);
})

Step to run the Node App:

node index.js

Output:

undefined

Error Handling

When using fs.readFile(), it’s important to handle errors properly to prevent crashes and ensure graceful error recovery. Common errors include file not found, insufficient permissions, and I/O errors. You can handle errors by checking the err parameter passed to the callback function. If err is truthy, an error occurred during the reading process, and you should handle it accordingly.

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

Conclusion

The fs.readFile() method in Node.js provides a straightforward way to read file contents asynchronously. By understanding its syntax, parameters, usage, and error handling, you can effectively use it to read data from files in your Node.js applications. When working with file I/O operations, always remember to handle errors properly to ensure the reliability and stability of your applications.


Similar Reads

Node.js fsPromises.readFile() Method
The fsPromises.readFile() method is used to read the file. This method read the entire file into the buffer. To load the fs module, we use require() method. It Asynchronously reads the entire contents of a file. Syntax: fsPromises.readFile( path, options ) Parameters: The method accepts two parameters as mentioned above and described below: path: I
2 min read
Node.js filehandle.readFile() Method
The filehandle.readFile() method is used to asynchronously read the file contents. This method reads the entire file into the buffer. It Asynchronously reads the entire contents of a file. Syntax: filehandle.readFile( options ) Parameters: The method accepts single parameter as mentioned above and described below: options: It holds the encoding of
2 min read
How to operate callback-based fs.readFile() method with promises in Node.js ?
The fs.readFile() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The readFile() method is used to asynchronously read the entire contents of a file and returns the buffer form of the data. The fs.readFile() method is based on callback. Using callback
5 min read
Difference between readFile and createReadStream in Node.js
Node.js offers various methods for file handling, two of the most commonly used being readFile and createReadStream. fs.readFile and fs.createReadStream are both used to read files in Node.js, but they cater to different needs. fs.readFile reads the entire file into memory, making it suitable for smaller files. In contrast, fs.createReadStream read
5 min read
PHP | readfile( ) Function
The readfile() function in PHP is an inbuilt function which is used to read a file and write it to the output buffer. The filename is sent as a parameter to the readfile() function and it returns the number of bytes read on success, or FALSE and an error on failure. By adding an '@' in front of the function name the error output can be hidden. Synt
2 min read
How to create a simple web server that can read a given file on a given disk via “readFile” function ?
To create a web server we need to import the 'http' module using require() method and create a server using the createServer() method of the HTTP module. Syntax: const http = require('http') const server = createServer(callback).listen(port,hostname); Now in the callback in the createServer() method, we need to read the file from our local director
3 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
three90RightbarBannerImg