Created
July 23, 2017 01:01
-
-
Save luveti/0feb570655a9e3419acd5c7b70f24218 to your computer and use it in GitHub Desktop.
promisify an entire nodejs module using util.promisify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function promisifyAll(module, callbackParameterName) { | |
const util = require('util') | |
function isFunction(f) { | |
return f && Object.prototype.toString.call(f) === '[object Function]' | |
} | |
if (!callbackParameterName) callbackParameterName = 'callback' | |
Object.keys(module) | |
.forEach(key => { | |
if (!isFunction(module[key])) return | |
let args = module[key].toString().match(/function\s.*?\(([^)]*)\)/)[1].split(',') | |
.map(arg => arg.replace(/\/\*.*\*\//, '').trim()) | |
.filter(arg => arg) | |
if (args.length == 0 || args[args.length - 1] != callbackParameterName) return | |
module[key] = util.promisify(module[key]) | |
}) | |
return module | |
} | |
// async / await example | |
const fs = promisifyAll(require('fs')) | |
;(async function() { | |
try { | |
await fs.writeFile('hello.txt', 'Hello world!') | |
} | |
catch (e) { | |
console.error(e) | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment