diff --git a/.gitattributes b/.gitattributes index 391f0a4..6313b56 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1 @@ -* text=auto -*.js text eol=lf +* text=auto eol=lf diff --git a/.travis.yml b/.travis.yml index f98fed0..94ab01f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,4 +2,3 @@ language: node_js node_js: - '12' - '10' - - '8' diff --git a/index.js b/index.js index ccbee49..a3877e1 100644 --- a/index.js +++ b/index.js @@ -1,11 +1,11 @@ 'use strict'; -const processFn = (fn, options, proxy, unwrapped) => function (...args) { +const processFn = (fn, options, proxy, unwrapped) => function (...arguments_) { const P = options.promiseModule; return new P((resolve, reject) => { if (options.multiArgs) { - args.push((...result) => { + arguments_.push((...result) => { if (options.errorFirst) { if (result[0]) { reject(result); @@ -18,7 +18,7 @@ const processFn = (fn, options, proxy, unwrapped) => function (...args) { } }); } else if (options.errorFirst) { - args.push((error, result) => { + arguments_.push((error, result) => { if (error) { reject(error); } else { @@ -26,26 +26,27 @@ const processFn = (fn, options, proxy, unwrapped) => function (...args) { } }); } else { - args.push(resolve); + arguments_.push(resolve); } const self = this === proxy ? unwrapped : this; - Reflect.apply(fn, self, args); + Reflect.apply(fn, self, arguments_); }); }; const filterCache = new WeakMap(); module.exports = (input, options) => { - options = Object.assign({ - exclude: [/.+(Sync|Stream)$/], + options = { + exclude: [/.+(?:Sync|Stream)$/], errorFirst: true, - promiseModule: Promise - }, options); + promiseModule: Promise, + ...options + }; - const objType = typeof input; - if (!(input !== null && (objType === 'object' || objType === 'function'))) { - throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objType}\``); + const objectType = typeof input; + if (!(input !== null && (objectType === 'object' || objectType === 'function'))) { + throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${input === null ? 'null' : objectType}\``); } const filter = (target, key) => { @@ -85,26 +86,26 @@ module.exports = (input, options) => { }, get(target, key) { - const prop = target[key]; + const property = target[key]; // eslint-disable-next-line no-use-extend-native/no-use-extend-native - if (!filter(target, key) || prop === Function.prototype[key]) { - return prop; + if (!filter(target, key) || property === Function.prototype[key]) { + return property; } - const cached = cache.get(prop); + const cached = cache.get(property); if (cached) { return cached; } - if (typeof prop === 'function') { - const pified = processFn(prop, options, proxy, target); - cache.set(prop, pified); + if (typeof property === 'function') { + const pified = processFn(property, options, proxy, target); + cache.set(property, pified); return pified; } - return prop; + return property; } }); diff --git a/license b/license index e7af2f7..fa7ceba 100644 --- a/license +++ b/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (sindresorhus.com) +Copyright (c) Sindre Sorhus (https://sindresorhus.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/optimization-test.js b/optimization-test.js index d708ff6..38abd5b 100644 --- a/optimization-test.js +++ b/optimization-test.js @@ -26,19 +26,20 @@ function assertOptimized(fn, name) { } } -const sut = pify({ - unicorn: cb => { - cb(null, 'unicorn'); +const fn = pify({ + unicorn: callback => { + callback(null, 'unicorn'); } }); -sut.unicorn().then(() => { - v8.optimizeFunctionOnNextCall(sut.unicorn); - - return sut.unicorn().then(() => { - assertOptimized(sut.unicorn, 'unicorn'); - }); -}).catch(error => { - console.error(error.stack); - process.exit(1); // eslint-disable-line unicorn/no-process-exit -}); +(async () => { + try { + await fn.unicorn(); + v8.optimizeFunctionOnNextCall(fn.unicorn); + await fn.unicorn(); + assertOptimized(fn.unicorn, 'unicorn'); + } catch (error) { + console.error(error); + process.exit(1); // eslint-disable-line unicorn/no-process-exit + } +})(); diff --git a/package.json b/package.json index 68c09bd..6919a6f 100644 --- a/package.json +++ b/package.json @@ -4,13 +4,14 @@ "description": "Promisify a callback-style function", "license": "MIT", "repository": "sindresorhus/pify", + "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" + "url": "https://sindresorhus.com" }, "engines": { - "node": ">=6" + "node": ">=10" }, "scripts": { "test": "xo && ava", @@ -20,14 +21,12 @@ "index.js" ], "keywords": [ + "promisify", + "callback", "promise", "promises", - "promisify", - "all", "denodify", "denodeify", - "callback", - "cb", "node", "then", "thenify", @@ -36,7 +35,6 @@ "wrap", "wrapper", "bind", - "to", "async", "await", "es2015", @@ -46,6 +44,6 @@ "ava": "^2.4.0", "pinkie-promise": "^2.0.0", "v8-natives": "^1.1.0", - "xo": "^0.23.0" + "xo": "^0.26.1" } } diff --git a/readme.md b/readme.md index fc65118..9a190ce 100644 --- a/readme.md +++ b/readme.md @@ -2,14 +2,12 @@ > Promisify a callback-style function - ## Install ``` $ npm install pify ``` - ## Usage ```js @@ -17,19 +15,18 @@ const fs = require('fs'); const pify = require('pify'); (async () => { - // Promisify a single function + // 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 + // 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?) @@ -48,7 +45,7 @@ Type: `object` ##### multiArgs -Type: `boolean`
+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. @@ -72,14 +69,14 @@ Methods in a module to promisify. Remaining methods will be left untouched. ##### exclude -Type: `Array`
-Default: `[/.+(Sync|Stream)$/]` +Type: `Array`\ +Default: `[/.+(?:Sync|Stream)$/]` Methods in a module **not** to promisify. Methods with names ending with `'Sync'` are excluded by default. ##### excludeMain -Type: `boolean`
+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. @@ -98,7 +95,7 @@ fn.method = (data, callback) => { }; (async () => { - // Promisify methods but not `fn()` + // Promisify methods but not `fn()`. const promiseFn = pify(fn, {excludeMain: true}); if (promiseFn()) { @@ -109,7 +106,7 @@ fn.method = (data, callback) => { ##### errorFirst -Type: `boolean`
+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. @@ -120,7 +117,6 @@ Type: `Function` Custom promise module to use instead of the native one. - ## FAQ #### How is this different from Node.js's [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)? @@ -131,14 +127,12 @@ Custom promise module to use instead of the native one. - Pify has useful options like the ability to handle multiple arguments (`multiArgs`). - Pify does not have [magic behavior](https://nodejs.org/api/util.html#util_custom_promisified_functions) for certain Node.js methods and instead focuses on predictability. - ## Related - [p-event](https://github.com/sindresorhus/p-event) - Promisify an event by waiting for it to be emitted - [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently - [More…](https://github.com/sindresorhus/promise-fun) - ---
diff --git a/test.js b/test.js index 23aad44..06c19a7 100644 --- a/test.js +++ b/test.js @@ -1,22 +1,35 @@ +/* eslint-disable promise/prefer-await-to-then */ import util from 'util'; import fs from 'fs'; import stream from 'stream'; import test from 'ava'; import pinkiePromise from 'pinkie-promise'; -import m from '.'; - -const fixture = cb => setImmediate(() => cb(null, 'unicorn')); -const fixture1 = cb => setImmediate(() => cb('error', 'unicorn', 'rainbow')); -const fixture2 = (x, cb) => setImmediate(() => cb(null, x)); -const fixture3 = cb => setImmediate(() => cb(null, 'unicorn', 'rainbow')); -const fixture4 = cb => setImmediate(() => { - cb(null, 'unicorn'); +import pify from '.'; + +const fixture = callback => setImmediate(() => { + callback(null, 'unicorn'); +}); + +const fixture1 = callback => setImmediate(() => { + callback('error', 'unicorn', 'rainbow'); +}); + +const fixture2 = (value, callback) => setImmediate(() => { + callback(null, value); +}); + +const fixture3 = callback => setImmediate(() => { + callback(null, 'unicorn', 'rainbow'); +}); + +const fixture4 = callback => setImmediate(() => { + callback(null, 'unicorn'); return 'rainbow'; }); -fixture4.meow = cb => { +fixture4.meow = callback => { setImmediate(() => { - cb(null, 'unicorn'); + callback(null, 'unicorn'); }); }; @@ -40,65 +53,69 @@ function FixtureClass() { this.instanceMethod1 = fixture; this.instanceValue1 = 72; } + util.inherits(FixtureClass, FixtureParent); FixtureClass.prototype.method1 = fixture; -FixtureClass.prototype.method2Cb = function (cb) { - setImmediate(() => cb(null, this.instanceValue1)); +FixtureClass.prototype.method2Cb = function (callback) { + setImmediate(() => { + callback(null, this.instanceValue1); + }); }; -FixtureClass.prototype.method2Async = m(FixtureClass.prototype.method2Cb); + +FixtureClass.prototype.method2Async = pify(FixtureClass.prototype.method2Cb); FixtureParent.prototype.overriddenValue1 = 4; FixtureClass.prototype.value1 = 'neo'; test('main', async t => { - t.is(typeof m(fixture)().then, 'function'); - t.is(await m(fixture)(), 'unicorn'); + t.is(typeof pify(fixture)().then, 'function'); + t.is(await pify(fixture)(), 'unicorn'); }); test('throw error on invalid input', t => { - let error = t.throws(() => m()); + let error = t.throws(() => pify()); t.is(error.message, 'Expected `input` to be a `Function` or `Object`, got `undefined`'); - error = t.throws(() => m('')); + error = t.throws(() => pify('')); t.is(error.message, 'Expected `input` to be a `Function` or `Object`, got `string`'); - error = t.throws(() => m(null)); + error = t.throws(() => pify(null)); t.is(error.message, 'Expected `input` to be a `Function` or `Object`, got `null`'); }); test('error', async t => { - t.is(await m(fixture1)().catch(error => error), 'error'); + t.is(await pify(fixture1)().catch(error => error), 'error'); }); test('pass argument', async t => { - t.is(await m(fixture2)('rainbow'), 'rainbow'); + t.is(await pify(fixture2)('rainbow'), 'rainbow'); }); test('custom Promise module', async t => { - t.is(await m(fixture, {promiseModule: pinkiePromise})(), 'unicorn'); + t.is(await pify(fixture, {promiseModule: pinkiePromise})(), 'unicorn'); }); test('multiArgs option', async t => { - t.deepEqual(await m(fixture3, {multiArgs: true})(), ['unicorn', 'rainbow']); + t.deepEqual(await pify(fixture3, {multiArgs: true})(), ['unicorn', 'rainbow']); }); test('multiArgs option — rejection', async t => { - t.deepEqual(await m(fixture1, {multiArgs: true})().catch(error => error), ['error', 'unicorn', 'rainbow']); + t.deepEqual(await pify(fixture1, {multiArgs: true})().catch(error => error), ['error', 'unicorn', 'rainbow']); }); test('wrap core method', async t => { - t.is(JSON.parse(await m(fs.readFile)('package.json')).name, 'pify'); + t.is(JSON.parse(await pify(fs.readFile)('package.json')).name, 'pify'); }); test('module support', async t => { - t.is(JSON.parse(await m(fs).readFile('package.json')).name, 'pify'); + t.is(JSON.parse(await pify(fs).readFile('package.json')).name, 'pify'); }); test('module support - doesn\'t transform *Sync methods by default', t => { - t.is(JSON.parse(m(fs).readFileSync('package.json')).name, 'pify'); + t.is(JSON.parse(pify(fs).readFileSync('package.json')).name, 'pify'); }); test('module support - doesn\'t transform *Stream methods by default', t => { - t.true(m(fs).createReadStream('package.json') instanceof stream.Readable); + t.true(pify(fs).createReadStream('package.json') instanceof stream.Readable); }); test('module support - preserves non-function members', t => { @@ -107,11 +124,11 @@ test('module support - preserves non-function members', t => { nonMethod: 3 }; - t.deepEqual(Object.keys(module), Object.keys(m(module))); + t.deepEqual(Object.keys(module), Object.keys(pify(module))); }); test('module support - transforms only members in options.include', t => { - const pModule = m(fixtureModule, { + const pModule = pify(fixtureModule, { include: ['method1', 'method2'] }); @@ -121,7 +138,7 @@ test('module support - transforms only members in options.include', t => { }); test('module support - doesn\'t transform members in options.exclude', t => { - const pModule = m(fixtureModule, { + const pModule = pify(fixtureModule, { exclude: ['method3'] }); @@ -131,7 +148,7 @@ test('module support - doesn\'t transform members in options.exclude', t => { }); test('module support - options.include over options.exclude', t => { - const pModule = m(fixtureModule, { + const pModule = pify(fixtureModule, { include: ['method1', 'method2'], exclude: ['method2', 'method3'] }); @@ -142,14 +159,14 @@ test('module support - options.include over options.exclude', t => { }); test('module support — function modules', t => { - const pModule = m(fixture4); + const pModule = pify(fixture4); t.is(typeof pModule().then, 'function'); t.is(typeof pModule.meow().then, 'function'); }); test('module support — function modules exclusion', t => { - const pModule = m(fixture4, { + const pModule = pify(fixture4, { excludeMain: true }); @@ -158,19 +175,19 @@ test('module support — function modules exclusion', t => { }); test('`errorFirst` option', async t => { - const fixture = (foo, cb) => { - cb(foo); + const fixture = (foo, callback) => { + callback(foo); }; - t.is(await m(fixture, {errorFirst: false})('🦄'), '🦄'); + t.is(await pify(fixture, {errorFirst: false})('🦄'), '🦄'); }); test('`errorFirst` option and `multiArgs`', async t => { - const fixture = (foo, bar, cb) => { - cb(foo, bar); + const fixture = (foo, bar, callback) => { + callback(foo, bar); }; - t.deepEqual(await m(fixture, { + t.deepEqual(await pify(fixture, { errorFirst: false, multiArgs: true })('🦄', '🌈'), ['🦄', '🌈']); @@ -179,14 +196,14 @@ test('`errorFirst` option and `multiArgs`', async t => { test('class support - does not create a copy', async t => { const obj = { x: 'foo', - y(cb) { + y(callback) { setImmediate(() => { - cb(null, this.x); + callback(null, this.x); }); } }; - const pified = m(obj); + const pified = pify(obj); obj.x = 'bar'; t.is(await pified.y(), 'bar'); @@ -195,7 +212,7 @@ test('class support - does not create a copy', async t => { test('class support — transforms inherited methods', t => { const instance = new FixtureClass(); - const pInstance = m(instance); + const pInstance = pify(instance); t.is(instance.value1, pInstance.value1); t.is(typeof pInstance.instanceMethod1().then, 'function'); @@ -206,14 +223,14 @@ test('class support — transforms inherited methods', t => { test('class support — preserves prototype', t => { const instance = new FixtureClass(); - const pInstance = m(instance); + const pInstance = pify(instance); t.true(pInstance instanceof FixtureClass); }); test('class support — respects inheritance order', async t => { const instance = new FixtureClass(); - const pInstance = m(instance); + const pInstance = pify(instance); t.is(instance.overriddenValue1, pInstance.overriddenValue1); t.is(await pInstance.overriddenMethod1('rainbow'), 'rainbow'); @@ -221,7 +238,7 @@ test('class support — respects inheritance order', async t => { test('class support - transforms only members in options.include, copies all', t => { const instance = new FixtureClass(); - const pInstance = m(instance, { + const pInstance = pify(instance, { include: ['parentMethod1'] }); @@ -232,7 +249,7 @@ test('class support - transforms only members in options.include, copies all', t test('class support - doesn\'t transform members in options.exclude', t => { const instance = new FixtureClass(); - const pInstance = m(instance, { + const pInstance = pify(instance, { exclude: ['grandparentMethod1'] }); @@ -242,7 +259,7 @@ test('class support - doesn\'t transform members in options.exclude', t => { test('class support - options.include over options.exclude', t => { const instance = new FixtureClass(); - const pInstance = m(instance, { + const pInstance = pify(instance, { include: ['method1', 'parentMethod1'], exclude: ['parentMethod1', 'grandparentMethod1'] }); @@ -258,24 +275,34 @@ test('promisify prototype function', async t => { }); test('method mutation', async t => { - const obj = { - foo(cb) { - setImmediate(() => cb(null, 'original')); + const object = { + foo(callback) { + setImmediate(() => { + callback(null, 'original'); + }); } }; - const pified = m(obj); + const pified = pify(object); - obj.foo = cb => setImmediate(() => cb(null, 'new')); + object.foo = callback => setImmediate(() => { + callback(null, 'new'); + }); t.is(await pified.foo(), 'new'); }); test('symbol keys', async t => { await t.notThrowsAsync(async () => { - const sym = Symbol('sym'); - const obj = {[sym]: cb => setImmediate(cb)}; - const pified = m(obj); - await pified[sym](); + const symbol = Symbol('symbol'); + + const object = { + [symbol]: callback => { + setImmediate(callback); + } + }; + + const pified = pify(object); + await pified[symbol](); }); }); @@ -284,62 +311,70 @@ test('symbol keys', async t => { // target object property if the target object property is a non-writable, // non-configurable own data property. test('non-writable non-configurable property', t => { - const obj = {}; - Object.defineProperty(obj, 'prop', { - value: cb => setImmediate(cb), + const object = {}; + Object.defineProperty(object, 'prop', { + value: callback => { + setImmediate(callback); + }, writable: false, configurable: false }); - const pified = m(obj); - t.notThrows(() => Reflect.get(pified, 'prop')); + const pified = pify(object); + t.notThrows(() => { + Reflect.get(pified, 'prop'); + }); }); test('do not promisify Function.prototype.bind', async t => { - function fn(cb) { - cb(null, this); + function fn(callback) { + callback(null, this); } + const target = {}; - t.is(await m(fn).bind(target)(), target); + t.is(await pify(fn).bind(target)(), target); }); test('do not break internal callback usage', async t => { - const obj = { - foo(cb) { - this.bar(4, cb); + const object = { + foo(callback) { + this.bar(4, callback); }, - bar(...args) { - const cb = args.pop(); - cb(null, 42); + bar(...arguments_) { + const callback = arguments_.pop(); + callback(null, 42); } }; - t.is(await m(obj).foo(), 42); + t.is(await pify(object).foo(), 42); }); test('Function.prototype.call', async t => { - function fn(...args) { - const cb = args.pop(); - cb(null, args.length); + function fn(...arguments_) { + const callback = arguments_.pop(); + callback(null, arguments_.length); } - const pified = m(fn); + + const pified = pify(fn); t.is(await pified.call(), 0); }); test('Function.prototype.apply', async t => { - function fn(...args) { - const cb = args.pop(); - cb(null, args.length); + function fn(...arguments_) { + const callback = arguments_.pop(); + callback(null, arguments_.length); } - const pified = m(fn); + + const pified = pify(fn); t.is(await pified.apply(), 0); }); test('self as member', async t => { - function fn(...args) { - const cb = args.pop(); - cb(null, args.length); + function fn(...arguments_) { + const callback = arguments_.pop(); + callback(null, arguments_.length); } + fn.self = fn; - const pified = m(fn); + const pified = pify(fn); t.is(await pified.self(), 0); });