How to operate callback-based fs.readFile() method with promises in Node.js ?
Last Updated :
18 Jul, 2020
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 method leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way.
Syntax:
fs.readFile(path, options)
Note: Callback not required since we operate the method with promises.
Parameters: This method accept two parameters as mentioned above and described below:
- path: It is a String, Buffer or URL that specifies the path to the file whose contents we try to read.
- options: It is an optional parameter which affects the output in someway accordingly we provide it to the function call or not.
- encoding: It is a string that specifies the encoding technique, default is null.
- flag: It is a string that specifies the file system flags. Its default value is ‘r’.
Approach: The fs.readFile() method based on callback. To operate it with promises, first, we use promisify() method defined in the utilities module to convert it into a promise based method.
Example 1: Filename: index.js
const fs = require( 'fs' )
const util = require( 'util' )
const readFileContent = util.promisify(fs.readFile)
readFileContent( './testFile.txt' )
.then(buff => {
const contents = buff.toString()
console.log(`\nContents of the file :\n${contents}`)
})
. catch (err => {
console.log(`Error occurs, Error code -> ${err.code},
Error No -> ${err.errno}`);
});
|
Implementing the same functionality using async-await.
const fs = require( 'fs' )
const util = require( 'util' )
const readFileContent = util.promisify(fs.readFile)
const fetchFile = async (path) => {
const buff = await readFileContent(path)
const contents = buff.toString()
console.log(`\nContents of the file :\n${contents}`)
}
fetchFile( './testFile.txt' )
. catch (err => {
console.log(`Error Occurs, Error code -> ${err.code},
Error NO -> ${err.errno}`);
});
|
Run the index.js file using the following command:
node index.js
Output:

Example 2: If given path to the file does not exist.
Filename: index.js
const fs = require( 'fs' )
const util = require( 'util' )
const readFileContent = util.promisify(fs.readFile)
readFileContent( './false/path.txt' )
.then(buff => {
const contents = buff.toString()
console.log(`\nContents of the file :\n${contents}`)
})
. catch (err => {
console.log(`\nError occurs, Error code -> ${err.code},
Error No -> ${err.errno}`);
})
|
Implementing the same functionality using async-await.
const fs = require( 'fs' )
const util = require( 'util' )
const readFileContent = util.promisify(fs.readFile)
const fetchFile = async (path) => {
const buff = await readFileContent(path)
const contents = buff.toString()
console.log(`\nContents of the file :\n${contents}`)
}
fetchFile( './false/path' )
. catch (err => {
console.log(`\nError Occurs, Error code -> ${err.code},
Error NO -> ${err.errno}`);
});
|
Run the index.js file using the following command:
node index.js
Output:

Explanation: The fs.readFile() method reads the contents of the file and hence it expected a path to the file that exist. Since the given path to the file does not exist, an error occurs with error code ‘ENOENT’ and error number ‘-4058’. The ‘ENOENT’ error occurs when a specified pathname does not exist.
Example 3: When given path is path to a folder not file.
Filename: index.js
const fs = require( 'fs' )
const util = require( 'util' )
const readFileContent = util.promisify(fs.readFile)
readFileContent( './testFolder' )
.then(buff => {
const contents = buff.toString()
console.log(`\nContents of the file :\n${contents}`)
})
. catch (err => {
console.log(`\nError occurs, Error code -> ${err.code},
Error No -> ${err.errno}`);
});
|
Implementing the same functionality using async-await.
const fs = require( 'fs' )
const util = require( 'util' )
const readFileContent = util.promisify(fs.readFile)
const fetchFile = async (path) => {
const buff = await readFileContent(path)
const contents = buff.toString()
console.log(`\nContents of the file :\n${contents}`)
}
fetchFile( './testFolder' )
. catch (err => {
console.log(`\nError Occurs, Error code -> ${err.code},
Error NO -> ${err.errno}`);
});
|
Run the index.js file using the following command:
node index.js
Output:

Explanation: The fs.readFile() method reads the contents of the file and hence it expected path to a file. Since the given path is a path to a folder, an error occurs with error code ‘EISDIR’ and error number ‘-4068’. The ‘EISDIR’ error occurs when an operation expected a file, but the pathname of directory is given.
Similar Reads
How to operate callback-based fs.readdir() method with promises in Node.js ?
The fs.readdir() 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 readdir() method is used to read the contents of a directory. The fs.readdir() method is based on callback. Using callback methods l
3 min read
How to operate callback-based fs.rename() method with promises in Node.js ?
The fs.rename() method is defined in the File System module of Node.js. The File System module is basically to interact with hard-disk of the userâs computer. The rename() method is used to rename the file at the given old path to a given new path. If the new path file already exists, it will be ove
5 min read
How to operate callback-based fs.mkdir() method with promises in Node.js ?
The fs.mkdir() 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 mkdir() method is used to asynchronously create a directory. The fs.mkdir() method is based on callback. Using callback methods leads
4 min read
How to operate callback-based fs.lstat() method with promises in Node.js ?
The fs.lstat() 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 lstat() method gives some information specific to files and folders using methods define on stats objects (data provided by lstat).The
4 min read
How to operate callback-based fs.truncate() method with promises in Node.js ?
The fs.truncate() method 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 truncate() method is used to modify the inner contents of the file by âlenâ bytes. If len is shorter than the fileâs current length, t
4 min read
How to operate callback-based fs.opendir() method with promises in Node.js ?
The fs.opendir() 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 method used to asynchronously open a directory.The fs.opendir() method is based on callback. Using callback methods leads to a great
5 min read
How to operate callback based fs.writeFile() method with promises in Node.js ?
The fs.writeFile() is a method 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 fs.writeFile() method asynchronously writes data to a file, replacing the file if it already exists. The fs.writeFile() method i
5 min read
How to operate callback based fs.appendFile() method with promises in Node.js ?
The fs.appendFile() 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 appendFile() method is used to append new data in the existing file or if the file does not exist then the file is created first
4 min read
How to convert function call with two callbacks promise in Node.js ?
Promise: Promise is used to handle the result, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block. A promise looks like this - function() .then(data => { // After promise is fulfilled console.log(data); })
3 min read
How to Convert an Existing Callback to a Promise in Node.js ?
Node.js, by nature, uses an asynchronous, non-blocking I/O model, which often involves the use of callbacks. While callbacks are effective, they can lead to complex and hard-to-read code, especially in cases of nested callbacks, commonly known as "callback hell." Promises provide a cleaner, more rea
7 min read