Reputation: 91
I know that node.js uses asynchronous behaviour. and the reason I am trying to save the response in my file system is coming to be "undefined". actually, until the response comes, the file is saved with "undefined" data.
this is my code
request(options, function (error, response, body){
if(!error){
console.log(body); //gives the response successfully
fs.writeFile("E:/FirebaseNotif/testfile", body.notification_key, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!"); //saves but with an "undefined" data
});
}else{
console.log('this is false');
}
});
How to handle this kind of asynchronous behaviour
Upvotes: 0
Views: 433
Reputation: 471
The issue request returns a response in a string so body variable contains string value, not JSON. You need to cast the response in JSON and use the variables
Try following after receving response
console.log(body);
const data = JSON.parse(body);
fs.writeFile('testfile', data.notification_key, function (err) {
if (err) {
return console.log(err);
}
console.log('The file was saved!');
});
Upvotes: 1