The `util.promisify()` Function in Node.js
In this post, we will give you information about The `util.promisify()` Function in Node.js – onlinecode. Here we will give you detail about The `util.promisify()` Function in Node.js – onlinecode And how to use it also give you a demo for it if it is necessary.
Node.js’ built-in util
package has a promisify()
function that converts callback-based functions to promise-based functions. This lets you use promise chaining and async/await with callback-based APIs.
For example, Node.js’ fs
package uses callbacks. Normally, to read a file, you would need to use callbacks:
const fs = require('fs');
fs.readFile('./package.json', function callback(err, buf) {
const obj = JSON.parse(buf.toString('utf8'));
obj.name; // 'onlinecode.org'
});
You can use util.promisify()
to convert the fs.readFile()
function
to a function that returns a callback:
const fs = require('fs');
const util = require('util');
// Convert 'fs.readFile()' into a function that takes the
// same parameters but returns a promise.
const readFile = util.promisify(fs.readFile);
// You can now use 'readFile()' with 'await'!
const buf = await readFile('./package.json');
const obj = JSON.parse(buf.toString('utf8'));
obj.name; // 'onlinecode.org'
Assumptions forĀ The `util.promisify()` Function in Node.js
How does util.promisify()
work under the hood? There’s a polyfill on npm, you can read the full implementation here.
You can also find the Node.js implementation here, although, for educational purposes, the polyfill is a bit easier to read.
The key idea behind util.promisify()
is that it adds a callback function to the parameters you passed in. That callback function resolves or rejects the promise the promisified function returns.
That’s a bit of a mouthful, so here’s a very simplified example of a custom implementation of util.promisify()
.
const fs = require('fs');
// A simplified implementation of 'util.promisify()'. Doesn't
// cover all cases, don't use this in prod!
function promisify(fn) {
return function() {
const args = Array.prototype.slice.call(arguments);
return new Promise((resolve, reject) => {
fn.apply(this, [].concat(args).concat([(err, res) => {
if (err != null) {
return reject(err);
}
resolve(res);
}]));
});
};
}
// Convert 'fs.readFile()' into a function that takes the
// same parameters but returns a promise.
const readFile = promisify(fs.readFile);
// You can now use 'readFile()' with 'await'!
const buf = await readFile('./package.json');
const obj = JSON.parse(buf.toString('utf8'));
obj.name; // 'onlinecode.org'
So what does this mean? First, util.promisify()
adds 1 extra argument to the arguments you passed in, and then calls the original function with those new arguments. That means the underlying function needs to support that number of arguments. So if you’re calling a promisified function myFn()
with 2 parameters of types [String, Object]
, make sure the original function supports a call signature of [String, Object, Function]
.
Secondly, util.promisify()
has implications for function context.
Losing Context for The `util.promisify()` Function in Node.js
Losing context means that a function call ends up with the wrong value of this
. Losing context is a common problem for transformed functions:
class MyClass {
myCallbackFn(cb) {
cb(null, this);
}
}
const obj = new MyClass();
const promisified = require('util').promisify(obj.myCallbackFn);
const context = await promisified();
context; // 'undefined' instead of a 'MyClass' instance!
Remember that this
contains whatever object the function was a property of when it was called. So you can retain context by setting the promisified
function as a property of the same object:
class MyClass {
myCallbackFn(cb) {
cb(null, this);
}
}
const obj = new MyClass();
// Retain context because 'promisified' is a property of 'obj'
obj.promisified = require('util').promisify(obj.myCallbackFn);
const context = await obj.promisified();
context === obj; // true
More Node Tutorials
- Working with UUID in Node
- Using bcrypt-js to Hash Passwords in JavaScript
- Working with the Node.js assert Library
- Modify Authorized redirect_uris For Google OAuth
- Sleep in NodeJS
- Convert HTML to Pug
- Convert Pug to HTML
Node.js is an open-source, cross-platform JavaScript runtime environment. Node.js allows you to run JavaScript code outside of a web browser. This makes it possible to create a wide variety of applications, including web servers, real-time chat applications, and data processing pipelines.
Node.js is built on top of the V8 JavaScript engine, which is also used by Google Chrome. This means that Node.js applications can take advantage of the same performance and features as Chrome.
Node.js is a popular choice for building web servers. This is because Node.js is very efficient at handling concurrent requests. Node.js uses a non-blocking event loop to handle requests, which means that it can handle multiple requests at the same time without slowing down.
Node.js is also a good choice for building real-time chat applications. This is because Node.js is able to push data to clients in real time without the need for polling. This makes it possible to create a smooth and responsive user experience.
Node.js is a powerful tool that can be used to create a wide variety of applications. If you are looking for a JavaScript runtime environment that is fast, scalable, and efficient, then Node.js is a great choice.
Here are some of the benefits of using Node.js:
- Performance: Node.js is very efficient at handling concurrent requests. This makes it a good choice for building web servers and real-time chat applications.
- Scalability: Node.js is designed to scale horizontally. This means that you can add more nodes to your cluster to handle more traffic.
- Efficiency: Node.js uses a non-blocking event loop to handle requests. This makes it possible to handle multiple requests at the same time without slowing down.
- Community: Node.js has a large and active community. This means that there are many resources available to help you learn and use Node.js.
Hope this code and post will helped you for implement The `util.promisify()` Function in Node.js – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs