Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Node.js – util.promisify() Method
The util.promisify() method basically takes a function as an input that follows the common Node.js callback style, i.e., with a (err, value) and returns a version of the same that returns a promise instead of a callback.
Syntax
util.promisify(original)
Parameters
It takes only one parameter −
original −This parameter takes an input for the function and returns them as a promise.
Example 1
Create a file with the name "promisify.js" and copy the following code snippet. After creating the file, use the command "node promisify.js" to run this code.
// util.promisify() Demo example
// Importing the fs and util modules
const fs = require('fs');
const util = require('util');
// Reading the file using a promise & printing its text
const readFile = util.promisify(fs.readFile);
readFile('./promisify.js', 'utf8') // Reading the same file
.then((text) => {
console.log(text);
})
// Printing error if any
.catch((err) => {
console.log('Error', err);
});
In the above example, we have used the fs module to read the files. We have used util.promisify() method to convert the fs.readFile to a promise-based method. Now,the above method gives us a promise instead of a callback. Promise further has two methods "then" and "catch" that are used to get the function result.
Output
C:\home\node>> node promisify.js
// util.promisify() Demo example
// Importing the fs and util modules
const fs = require('fs');
const util = require('util');
// Reading the file using a promise & printing its text
const readFile = util.promisify(fs.readFile);
readFile('./util.js', 'utf8')
.then((text) => {
console.log(text);
})
// Printing error if any
.catch((err) => {
console.log('Error', err);
});
Example 2
Let’s have a look at one more example
// util.promisify() Demo example
// Importing the fs and util modules
const util = require('util')
const fs = require('fs')
// Changing from callback to promise based
const readdir = util.promisify(fs.readdir)
// Reading files
const readFiles = async (path) => {
const files = await readdir(path)
// Printing current working directory
console.log(files) //Print all files on current working directory
console.log(process.cwd())
}
readFiles(process.cwd()).catch(err => {
console.log(err)
})
Output
C:\home\node>> node promisify.js [ 'app.js', 'index.html', 'node_modules', 'package-lock.json', 'package.json', 'promisify.js', C:\home\node
