pify

中文文档
6.1.0发布于 2022/09/02MITTypeScriptES Module零依赖近 30 天下载 4.1亿

Promisify a callback-style function

原始使用文档
文档目录6 节
  1. Install
  2. Usage
  3. API
  4. pify(input, options?)
  5. FAQ
  6. Related

pify

Promisify a callback-style function

Install

npm install pify

Usage

import fs from 'fs';
import pify from 'pify';

// Promisify a single function.
const data = await pify(fs.readFile)('package.json', 'utf8');
console.log(JSON.parse(data).name);
//=> 'pify'

// Promisify all methods in a module.
const data2 = await pify(fs).readFile('package.json', 'utf8');
console.log(JSON.parse(data2).name);
//=> 'pify'

API

pify(input, options?)

Returns a Promise wrapped version of the supplied function or module.

input

Type: Function | object

Callback-style function or module whose methods you want to promisify.

options

Type: object

multiArgs

Type: boolean
Default: false

By default, the promisified function will only return the second argument from the callback, which works fine for most APIs. This option can be useful for modules like request that return multiple arguments. Turning this on will make it return an array of all arguments from the callback, excluding the error argument, instead of just the second argument. This also applies to rejections, where it returns an array of all the callback arguments, including the error.

import request from 'request';
import pify from 'pify';

const pRequest = pify(request, {multiArgs: true});

const [httpResponse, body] = await pRequest('https://sindresorhus.com');
include

Type: Array<string | RegExp>

Methods in a module to promisify. Remaining methods will be left untouched.

exclude

Type: Array<string | RegExp>
Default: [/.+(?:Sync|Stream)$/]

Methods in a module not to promisify. Methods with names ending with 'Sync' are excluded by default.

excludeMain

Type: boolean
Default: false

If the given module is a function itself, it will be promisified. Enable this option if you want to promisify only methods of the module.

import pify from 'pify';

function fn() {
    return true;
}

fn.method = (data, callback) => {
    setImmediate(() => {
        callback(null, data);
    });
};

// Promisify methods but not `fn()`.
const promiseFn = pify(fn, {excludeMain: true});

if (promiseFn()) {
    console.log(await promiseFn.method('hi'));
}
errorFirst

Type: boolean
Default: true

Whether the callback has an error as the first argument. You'll want to set this to false if you're dealing with an API that doesn't have an error as the first argument, like fs.exists(), some browser APIs, Chrome Extension APIs, etc.

promiseModule

Type: Function

Custom promise module to use instead of the native one.

FAQ

How is this different from Node.js's util.promisify?

  • Pify existed long before util.promisify.
  • Pify is faster.
  • Pify supports wrapping a whole module/object, not just a specific method.
  • Pify has useful options like the ability to handle multiple arguments (multiArgs).
  • Pify does not have magic behavior for certain Node.js methods and instead focuses on predictability.

How can I promisify a single class method?

Class methods are not bound, so when they're not called on the class itself, they don't have any context. You can either promisify the whole class or use .bind().

import pify from 'pify';
import SomeClass from './some-class.js';

const someInstance = new SomeClass();

// ❌ `someFunction` can't access its class context.
const someFunction = pify(someClass.someFunction);

// ✅ The whole class is promisified and the `someFunction` method is called on its class.
const someClassPromisified = pify(someClass);
someClassPromisified.someFunction();

// ✅ `someFunction` is bound to its class before being promisified.
const someFunction = pify(someClass.someFunction.bind(someClass));

Why is pify choosing the last function overload when using it with TypeScript?

If you're using TypeScript and your input has function overloads, then only the last overload will be chosen and promisified.

If you need to choose a different overload, consider using a type assertion:

function overloadedFunction(input: number, callback: (error: unknown, data: number => void): void
function overloadedFunction(input: string, callback: (error: unknown, data: string) => void): void {
    /* … */
}

const fn = pify(overloadedFunction as (input: number, callback: (error: unknown, data: number) => void) => void)
// ^ ? (input: number) => Promise<number>
  • p-event - Promisify an event by waiting for it to be emitted
  • p-map - Map over promises concurrently
  • More…

Get professional support for 'pify' with a Tidelift subscription
Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.

版本与发布记录

pify 共发布 13 个版本,首次发布于 2015/08/29;过去 12 个月发布了 0 个版本。

版本发布日期距今
6.1.0latest2022/09/024 年前
6.0.02022/06/064 年前
5.0.02020/02/156 年前
4.0.12018/10/228 年前
4.0.02018/08/098 年前
3.0.02017/05/289 年前

关于 pify 的常见问题

pify 是什么?

Promisify a callback-style function

如何安装 pify?

在项目目录运行 npm install pify,或使用 pnpm add / yarn add / bun add。

pify 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

pify 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

pify 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=14.16。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

pify 可以商用吗?

pify 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

pify 的下载量有多少?

根据 npm 官方下载统计,pify 在 2026/10/05 – 2026/11/03 这 30 天内被下载 406,065,783 次,日均约 13,535,526 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

pify 还在维护吗?

最新版本 6.1.0 发布于 2022/09/02(4 年前);至今共发布 13 个版本,其中过去 12 个月发布了 0 个;首次发布于 2015/08/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。