I wrote the below code snippet:
var data = require('./readFile.js');
const argv = require('./index.js');
const colors = require('colors');
const rp = require('request-promise').defaults({ encoding: null });
const memeImage = argv.name;
const path = './json/meme.json';
var myData;
data.readFile(path)
.then(function (value) {
var jsonData = JSON.parse(value);
const options = {
resolveWithFullResponse: true
}
jsonData.forEach(element => {
if(element.title == memeImage) {
rp.get(element.image, options)
.then(function(response){
if(response.statusCode == 200) {
myData = Buffer.from(response.body).toString('base64');
myData.replace('myData:image/png;base64,', '');
console.log(myData);
resolve(myData);
}
else {
console.log('Error in retrieving image. Status code: ', response.statusCode);
reject('Error in retrieving image.');
}
})
.catch(function(error){
console.log('Error in downloading the image via request()');
reject('Error in downloading the image via request()');
});
}
});
})
.then(function(myData) {
console.log(myData);
})
.catch(function(err) {
//Error in reading the file
console.log(err);
})
module.exports=myData;
Here, function readFile()
imported from a different file (readFile.js
) returned a promise. readFile.js
is as below:
var myData, obj, found=false;
function readFile(path) {
return new Promise(function(resolve, reject){
if(!fs.existsSync(path)) {
console.log('Will throw error now!');
reject("memes.json file does not exist");
}
else {
//File exists
console.log('File found');
var data = fs.readFileSync(path, 'utf8');
resolve(data);
}
})
}
module.exports.readFile = readFile;
Now in the topmost code snippet, my aim is to read a file (that maps a title to a URL) using the readFile.js
file and then download the image at the corresponding URL. Once this match is found (if clause above), the promise should be resolved and returned to a new module.
What happens right now is, I get the following output:
node ./lib/getImage.js -n title -t topText -b bottomText
File found
undefined
<... image ... as a base64 string>
Error in downloading the image via request()
Unhandled rejection ReferenceError: reject is not defined ...
My question is, answers such as this and this all talk about returning multiple promises from a loop. In my case, I just want to return a single promise resolve (depending upon the match) and just stop.
How do I achieve this?