Node util.promisify() Method
Last Updated :
14 Jan, 2024
`util.promisify()` in Node.js converts callback-based methods to promise-based, aiding in managing asynchronous code more cleanly. This alleviates callback nesting issues, enhancing code readability, and simplifying asynchronous operations through promise chaining.
Syntax:
util.promisify(func)
Parameters: This method accepts a single parameter function that holds the callback based function.
Return Value: This method returns a promise-based function.
Example 1: Below is the code example of the util.promisify() Method:
Javascript
const util = require( 'util' )
const fs = require( 'fs' )
const readdir =
util.promisify(fs.readdir)
readdir( 'process.cwd()' )
.then(files => {
console.log(files)
})
. catch (err => {
console.log(err)
})
|
Output:
[Error: ENOENT: no such file or directory,
scandir 'C:\Users\bhudk\Desktop\nodec\process.cwd()'] {
errno: -4058,
code: 'ENOENT',
syscall: 'scandir',
path: 'C:\\Users\\bhudk\\Desktop\\nodec\\process.cwd()'
}
Example 2: Below is the code example of the util.promisify() Method:
Javascript
const util = require( 'util' )
const fs = require( 'fs' )
const readdir = util.promisify(fs.readdir)
const readFiles = async (path) => {
const files = await readdir(path)
console.log(files)
}
readFiles(process.cwd()). catch (err => {
console.log(err)
})
|
Output:
Example 3: Below is the code example of the util.promisify() Method:
Javascript
const util = require( 'util' )
const fs = require( 'fs' )
const readdir = util.promisify(fs.readdir)
const lstat = util.promisify(fs.lstat)
const readFiles = async (path) => {
const files = await readdir(path)
for (let file of files) {
const stats = await lstat(file)
if (stats.isFile()) {
console.log(`${file} -----> File`)
} else {
console.log(`${file} -----> Folder`)
}
}
}
readFiles( 'process.cwd()' ). catch (err => {
console.log(err)
})
|
Output:
We have a Cheat Sheet on Node utility methods where we covered all the utility methods to check those please go through Node.js Utility Complete Reference article.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...