I'm likely reinventing the wheel here, but I want to make a function that takes a filename and returns the base64 encoded string asynchronously.
I'm really only familiar with callbacks, but trying to understand promises as well. My initial callback function looks like this --
blob2Base64callback.js
module.exports = {
blob2base64 : function(file) {
fs.readFile(file, 'utf8', function(err, contents){
if (err) {
console.log('file not found');
return '';
} else {
var base64str = Buffer.from(contents).toString('base64');
console.log(base64str.length);
return base64str;
}
});
}, //..other functions
};
This callback doesn't work because I'm not actually returning something from the blob2base4 function and if I modify this to something like the following:
module.exports = {
blob2base64 : function(file) {
return fs.readFile(file, 'utf8', function(err, contents){
//same implementation as above, cut to improve readability
});
}
};
It returns undefined because it doesn't wait to be executed. As far as I know, there is no possible way to return something to blob2base64 using callbacks.
So I looked into promises and tried the following:
blob2Base64promise.js
blob2base64 : function(file) {
console.log('function called');
const getFile = new Promise(function(resolve, reject){
fs.readFile(file, 'utf8', function(err, contents){
if (err) {
console.log('file not found');
reject(err)
} else {
//console.log(contents);
resolve(contents);
}
});
}).then(contents =>{
var base64str = Buffer.from(contents).toString('base64');
return base64str;
}).catch(err => console.log(err));
}
Is there anyway I can return the promise to the function and extract the resolve portion to get base64str? Am I right in thinking, this behavior is only possible with promises, but not callbacks. Or is it not possible with either syntax?
Also, I thought callbacks and promises couldn't be used together, yet this promise is just a wrapper around a callback.
getFile..then()callback to the returned Promise value.asyncandawait, which basically are ways of wrapping up Promise callback code in a less clumsy syntax.parse.blob2base64('file.pdf').then(val=> console.log(val));