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');
What if you want to do something like this
...
readMyFile('myfile', 'utf8')
.then(file => console.log('file', file)
...
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));
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));
Have fun
:)
Top comments (1)
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
.