putil-promisify

1.10.1 · maintenance · verified Sun Apr 19

putil-promisify is a lightweight utility designed for transforming traditional Node.js callback-style functions into Promise-based equivalents. Its current stable version is 1.10.1, indicating a mature and likely infrequently updated library, suggesting a maintenance release cadence. This package provides a straightforward API, primarily through `fromCallback`, to convert functions adhering to the `(err, data)` callback signature into Promise-returning functions. It serves as an alternative to Node.js's built-in `util.promisify` for scenarios requiring a minimal dependency or compatibility with Node.js versions older than 8.0.0 (though its `package.json` specifies Node.js >= 14.0), or for specific custom promisification needs where `util.promisify`'s behavior might not be ideal.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `fromCallback` to convert both a custom callback-style function and a Node.js built-in function (like `fs.readFile`) into Promise-based equivalents, then utilizes them with `async/await` for cleaner asynchronous code, including error handling.

import { fromCallback } from 'putil-promisify';
import * as fs from 'fs';

// A simple example of a callback-style function
function asyncOperation(value: string, callback: (err: Error | null, result?: string) => void) {
  setTimeout(() => {
    if (value === 'error') {
      return callback(new Error('Simulated error for: ' + value));
    }
    callback(null, 'Processed: ' + value.toUpperCase());
  }, 100);
}

// Promisify the callback-style function
const promisifiedAsyncOperation = fromCallback(asyncOperation);

// Use the promisified function with async/await
async function runExample() {
  try {
    const result1 = await promisifiedAsyncOperation('hello');
    console.log(result1);

    // Promisify a Node.js built-in function like fs.readFile
    const readFilePromise = fromCallback(fs.readFile);
    const fileContent = await readFilePromise('./package.json', 'utf8');
    console.log('\nContent of package.json (first 100 chars):\n', fileContent.substring(0, 100) + '...');

    const result2 = await promisifiedAsyncOperation('world');
    console.log(result2);

    // Demonstrate error handling
    await promisifiedAsyncOperation('error');
  } catch (error: any) {
    console.error('\nCaught an error:', error.message);
  }
}

runExample();

view raw JSON →