util.promisify Polyfill

1.1.3 · maintenance · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

Demonstrates how to apply `util.promisify` to both a custom callback-style function and a Node.js built-in function like `fs.readFile`, showcasing basic usage and error handling.

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();

view raw JSON →