util.promisify Polyfill
This package provides a polyfill or shim for the `util.promisify` function, which was introduced natively in Node.js v8.0.0. For environments running Node.js versions older than 8, it supplies its own implementation, enabling the use of Promise-based asynchronous patterns for callback-style functions. In Node.js v8.0.0 and later, it effectively becomes a passthrough, exporting the built-in `util.promisify`. The current stable version is 1.1.3. As a polyfill for a long-established native feature, its release cadence is very slow, primarily for bug fixes or to align with ancient Node.js environments. Its key differentiator is providing this core Node.js utility in environments where it's otherwise absent, making it crucial for maintaining compatibility across a wide range of Node.js versions, particularly in legacy applications that cannot upgrade past Node.js 7.x or older.
Common errors
-
ReferenceError: Promise is not defined
cause The runtime environment does not have a global Promise constructor, which is a requirement for this polyfill.fixProvide a Promise polyfill (e.g., `core-js/es6/promise`) before requiring `util.promisify` or ensure running in an environment with native Promise support. -
TypeError: util.promisify is not a function
cause The `util.promisify/shim` was required but not called as a function, or the package was not included at all.fixEnsure you correctly invoke the shim: `require('util.promisify/shim')();` before attempting to use `util.promisify`. -
SyntaxError: Use of const in strict mode.
cause This error or similar ES6+ syntax errors occur when the package is run in an extremely old JavaScript environment that does not fully support ES5, even though the package states it requires ES5.fixUpdate your JavaScript runtime or compilation target to fully support ES5. If targeting extremely old browsers, additional transpilation might be necessary for other parts of your codebase. -
TypeError: promisify.custom is not a function
cause Attempting to access `promisify.custom` (a Symbol used for custom promisification behavior) on the direct `promisify` export from this polyfill, instead of the native `util.promisify` or the shimmed `util.promisify` which supports the Symbol.fixIf custom promisification is needed, ensure you are using a Node.js environment >= v8 where the native `util.promisify` (which has `promisify.custom`) is available, or use the `util.promisify/shim` and access it via `util.promisify`.
Warnings
- gotcha This polyfill is primarily intended for Node.js environments older than v8.0.0. If you are using Node.js v8 or newer, the `util.promisify` function is built-in and does not require this package.
- gotcha The package explicitly requires a native ES5 environment and for the `Promise` global to be available. It will throw an error upon requiring if these prerequisites are not met.
- gotcha When using the shim (`require('util.promisify/shim')`), it must be invoked as a function (`shim()`) to apply the patch to the `util` module. Merely requiring it without calling the function will not define `util.promisify`.
- deprecated While still functional, the need for this package diminishes with each passing year as older Node.js versions become less common. Projects should aim to upgrade Node.js to v8 or higher to rely on the native `util.promisify`.
Install
-
npm install util.promisify -
yarn add util.promisify -
pnpm add util.promisify
Imports
- promisify
import { promisify } from 'util.promisify';const promisify = require('util.promisify'); - util.promisify (after shim)
require('util.promisify/shim');require('util.promisify/shim')(); - util.promisify
import { promisify } from 'util';const { promisify } = require('util');
Quickstart
import './node_modules/util.promisify/shim'; // Ensure the shim is loaded
import * as util from 'util';
import * as fs from 'fs';
// Example callback-style function
function delay(ms: number, callback: (err: Error | null, message?: string) => void): void {
setTimeout(() => {
if (ms < 0) {
callback(new Error('Delay must be positive'));
} else {
callback(null, `Delayed for ${ms} milliseconds.`);
}
}, ms);
}
// Promisify the custom function
const promisifiedDelay = util.promisify(delay);
// Promisify a built-in Node.js function (e.g., fs.readFile)
const readFilePromisified = util.promisify(fs.readFile);
async function runExample() {
try {
console.log('Starting delay...');
const result = await promisifiedDelay(1000);
console.log(result); // Expected: "Delayed for 1000 milliseconds."
// Demonstrate error handling
await promisifiedDelay(-100);
} catch (error: any) {
console.error('Caught expected error:', error.message); // Expected: "Delay must be positive"
}
try {
// Create a dummy file for demonstration
fs.writeFileSync('temp.txt', 'Hello, util.promisify!');
const data = await readFilePromisified('./temp.txt', 'utf8');
console.log('Read temp.txt:', data);
fs.unlinkSync('temp.txt'); // Clean up
} catch (err: any) {
console.error('Error reading/writing file:', err.message);
}
}
runExample();