Stable: 0.5.0
Maintained by Tim Branyen @tbranyen.
Wraps Node modules, functions, and methods written in the Node-callback style to return Promises.
npm install promisify-nodeWrap entire Node modules recursively:
varpromisify=require("promisify-node");varfs=promisify("fs");// This function has been identified as an asynchronous function so it has// been automatically wrapped.fs.readFile("/etc/passwd").then(function(contents){console.log(contents);});Wrap a single function:
varpromisify=require("promisify-node");functionasync(callback){callback(null,true);}// Convert the function to return a Promise.varwrap=promisify(async);// Invoke the newly wrapped function.wrap().then(function(value){console.log(value===true);});Wrap a method on an Object:
varpromisify=require("promisify-node");varmyObj={myMethod: function(a,b,cb){cb(a,b);}};// No need to return anything as the methods will be replaced on the object.promisify(myObj);// Intentionally cause a failure by passing an object and inspect the message.myObj.myMethod({msg: "Failure!"},null).then(null,function(err){console.log(err.msg);});Wrap without mutating the original:
varpromisify=require("promisify-node");varmyObj={myMethod: function(a,b,cb){cb(a,b);}};// Store the original method to check latervaroriginalMethod=myObj.myMethod;// Now store the result, since the 'true' value means it won't mutate 'myObj'.varpromisifiedObj=promisify(myObj,undefined,true);// Intentionally cause a failure by passing an object and inspect the message.promisifiedObj.myMethod({msg: "Failure!"},null).then(null,function(err){console.log(err.msg);});// The original method is still intactassert(myObj.myMethod===originalMethod);assert(promisifiedObj.myMethod!==myObj.myMethod);Run the tests after installing dependencies with:
npm test