DEV Community

Merlier
Merlier

Posted on

How to promisify node callbacks

Consider having a classic callback in NodeJS like this one:

const fs = require('fs');

function readMyFile(myfile, options) {
    fs.readFile(myfile, options, function(err, file) {
        if(err) {
            console.log('err', err);
        } else {
            console.log('file', file);
        }
    });
}

readMyFile('myfile', 'utf8');
Enter fullscreen mode Exit fullscreen mode

What if you want to do something like this

...
readMyFile('myfile', 'utf8')
    .then(file => console.log('file', file)
    ...
Enter fullscreen mode Exit fullscreen mode

You can manually tranform your callback into a promise like this:

const fs = require('fs');

function readMyFilePromise(myfile, options) {
    return new Promise((resolve, reject) => {
        fs.readFile(myfile, options, function(err, file) {
            if(err) {
                console.log('err', err);
                reject(err);
            } else {
                console.log('file', file);
                resolve(file);
            }
        });
    });
}

readMyFilePromise('myfile', 'utf8')
    .then(file => console.log('file', file))
    .catch(err => console.log('err', err));
Enter fullscreen mode Exit fullscreen mode

The good news is you can use the util module to do that. Moreover Util is built in nodejs.

You just have to do this:

const util = require('util');
const fs = require('fs');

const readPromise = util.promisify(fs.readFile);
readPromise('myfile', 'utf8')
    .then(file => console.log('file', file))
    .catch(err => console.log('err', err));

Enter fullscreen mode Exit fullscreen mode

Have fun
:)

Top comments (1)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

There is also promisifyAll, but you will need some library (e.g. Bluebird).

Furthermore, there is require('fs/promise').

Lastly, I generally prefer fs-extra.