Skip to content

Instantly share code, notes, and snippets.

@luveti
Created July 23, 2017 01:01
Show Gist options
  • Save luveti/0feb570655a9e3419acd5c7b70f24218 to your computer and use it in GitHub Desktop.
Save luveti/0feb570655a9e3419acd5c7b70f24218 to your computer and use it in GitHub Desktop.
promisify an entire nodejs module using util.promisify
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