putil-promisify
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
-
TypeError: Promisify.fromCallback is not a function
cause This error typically occurs when `putil-promisify` is imported incorrectly, either by attempting a direct named destructuring in CommonJS or an incorrect default import in ESM, preventing `fromCallback` from being accessed as a method.fixFor CommonJS, ensure you import the whole module first: `const Promisify = require('putil-promisify');`, then access `Promisify.fromCallback`. For ESM, use `import { fromCallback } from 'putil-promisify';` to directly import the named export. -
Error: The 'callback' argument must be a function
cause This error indicates that the function passed to `fromCallback` does not accept a callback as its last argument, or the argument provided is not callable. `putil-promisify` expects the input function to strictly adhere to the Node.js error-first callback signature.fixVerify that the function you are attempting to promisify accepts a `(error, result)` callback as its final argument. If it does not, you may need to wrap it in an adapter function that conforms to this signature before passing it to `fromCallback`.
Warnings
- deprecated Node.js has included a native `util.promisify` function since v8.0.0, which is the recommended standard for converting Node.js-style callback functions to Promises. For most modern Node.js applications (v8+), `util.promisify` from `node:util` is generally preferred as it is part of the runtime and often handles nuances more robustly.
- gotcha There is a discrepancy in the stated Node.js compatibility: the README claims `node >= 6.x`, but the `package.json` specifies `engines: {"node": ">= 14.0"}`. This suggests that while older Node.js versions *might* have been supported historically, the current official support is for Node.js v14.0 and newer.
- gotcha Like many promisification utilities, `putil-promisify` (and even `util.promisify`) is designed for functions that follow the Node.js error-first callback pattern `(err, result) => ...`. Functions that use non-standard callback signatures (e.g., `(data1, data2, err) => ...` or multiple success arguments `(err, result1, result2) => ...`) may not be promisified correctly, potentially leading to unexpected Promise resolutions or rejections.
Install
-
npm install putil-promisify -
yarn add putil-promisify -
pnpm add putil-promisify
Imports
- fromCallback (ESM)
import Promisify from 'putil-promisify'; // Incorrect default import, 'fromCallback' is a named export.
import { fromCallback } from 'putil-promisify'; - fromCallback (CommonJS)
const { fromCallback } = require('putil-promisify'); // The primary export is an object, not a direct destructure of 'fromCallback'.const Promisify = require('putil-promisify'); const promisifiedFunction = Promisify.fromCallback(callbackStyleFunction); - TypeScript types
import type { Promisify } from 'putil-promisify';
Quickstart
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();