Node.js Promisify Polyfill

3.0.0 · maintenance · verified Tue Apr 21

util-promisify is a JavaScript package that provides the `util.promisify` function from Node.js core as a standalone module. It was originally created to enable the use of `async/await` patterns with callback-based Node.js APIs in environments prior to Node.js 8, where `util.promisify` was initially introduced. While the current stable version is 3.0.0, the package's core functionality is now standard and natively available in all actively supported Node.js versions (v8.0.0 and later). Consequently, this package primarily serves as a polyfill for legacy Node.js environments. Its release cadence is infrequent, typically limited to minor maintenance updates or compatibility adjustments, rather than active feature development. The key differentiator at its inception was providing early access to this crucial utility for modernizing asynchronous code, though its necessity has significantly diminished due to its universal inclusion in recent Node.js runtimes. Developers targeting Node.js versions older than 8.0.0 would find this module essential, otherwise, the native `util.promisify` should be preferred for better performance and reduced dependency count.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `util-promisify` to convert Node.js callback-style functions (`fs.stat`, `fs.readFile`, `fs.writeFile`) into Promise-based equivalents, including basic file operations and error handling within an async function. Note that type definitions are typically provided by `@types/util-promisify`.

import promisify from 'util-promisify'; // Use const promisify = require('util-promisify'); for CommonJS
import * as fs from 'fs';
import { join } from 'path';

const statAsync = promisify(fs.stat);
const readFileAsync = promisify(fs.readFile);
const writeFileAsync = promisify(fs.writeFile);

async function demonstratePromisify() {
  const tempFilePath = join(process.cwd(), `temp_file_${Date.now()}.txt`);
  const fileContent = `Hello, util-promisify! This is a test content written at ${new Date().toISOString()}`; 

  try {
    console.log(`Attempting to write to: ${tempFilePath}`);
    await writeFileAsync(tempFilePath, fileContent, 'utf8');
    console.log(`Successfully wrote ${fileContent.length} bytes to ${tempFilePath}`);

    const stats = await statAsync(tempFilePath);
    console.log(`File stats: size=${stats.size} bytes, isFile=${stats.isFile()}`);

    const content = await readFileAsync(tempFilePath, 'utf8');
    console.log(`File content read: "${content}"`);

    // Example of error handling: trying to stat a non-existent file
    console.log('\nAttempting to stat a non-existent file for error demonstration...');
    await statAsync('/path/to/definitely/nonexistent/file.xyz');
  } catch (error: any) {
    if (error.code === 'ENOENT') {
      console.error(`Expected error: File or directory not found. Message: ${error.message}`);
    } else {
      console.error(`An unexpected error occurred: ${error.message}`);
    }
  } finally {
    if (fs.existsSync(tempFilePath)) {
      await promisify(fs.unlink)(tempFilePath);
      console.log(`Cleaned up temporary file: ${tempFilePath}`);
    } else {
      console.log(`No temporary file to clean up at ${tempFilePath}`);
    }
  }
}

demonstratePromisify().catch(err => {
  console.error("A fatal error occurred during the demonstration:", err);
});

view raw JSON →