Node JS fs.readFile() Method
Last Updated :
06 Jan, 2025
In Node, the fs (File System) module provides 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.
NodeJS readfile method
The readfile method is used to asynchronously read the data from a file. It is a method of node js file system module. Asynchronously reading file content enables the non-blocking operation in Node.
Syntax:
fs.readFile( file_path, encoding, callback_function )
Parameters:
The method accepts three parameters as mentioned above and described below:
- file_path: 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:

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
const 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 fs.readFile() Method
In Node, the fs (File System) module provides 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, par
3 min read
Node.js fs.exists() Method
The fs exists method in node is used to check if the input file or the directory exists or not. It is an inbuilt application programming interface of fs module which provides an API for interacting with the file system in a manner closely modeled around POSIX functions. Syntax:fs.exists( path, callb
2 min read
Node fs.existsSync() Method
The fs.existsSync Method in Node is used to synchronously check if a file exists in the given path or not. It returns a boolean value which indicates the existence of a file. Syntax:fs.existsSync( path )Parameters: This method accepts a single parameter as mentioned above and described below: path:
2 min read
Node fs.mkdir() Method
The fs.mkdir() method in Node.js is used to create a directory asynchronously. Syntax fs.mkdir(path, mode, callback)Parameters: This method accepts three parameters as mentioned above and described below: path: This parameter holds the path of the directory that has to be created.mode: This paramete
2 min read
Node.js fs.truncate() Method
The fs.truncate() method in node.js is used to change the size of the file i.e either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file's current length, the file is truncated to that length. If i
2 min read
Node.js fs.renameSync() Method
In Node.js, the fs.renameSync() method is part of the built-in File System (fs) module and is used to rename or move files and directories synchronously. This method is useful when you need to quickly change a file's name or move it to a different directory synchronously. It blocks the execution of
3 min read
Node.js fs.rmdir() Method
The fs.rmdir() method is used to delete a directory at the given path. It can also be used recursively to remove nested directories. Syntax: fs.rmdir( path, options, callback )Parameters: This method accepts three parameters as mentioned above and described below: path: It holds the path of the dire
3 min read
Node.js fs.stat() Method
The fs.stat() method is used to return information about the given file or directory. It returns an fs.Stat object which has several properties and methods to get details about the file or directory. Syntax:fs.stat( path, options, callback )Parameters: This method accept three parameters as mentione
4 min read
Node.js fs.mkdtempSync() Method
The fs.mkdtempSync() method is an inbuilt application programming interface of fs module which provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. The fs.mkdtempSync() method creates a unique temporary directory. This is the synchronous v
2 min read
Node.js fs.realpath() Method
The fs.realPath() method is used to compute the canonical pathname of the given path. It does so by resolving the ., .. and the symbolic links in the path. Syntax: fs.realpath( path, options, callback ) Parameters: This method accept three parameters as mentioned above and described below: path: It
3 min read