I want to make a node script that save in json files some news that i get from a rss feed. I have a objects with some urls and i try to loop over this, make the request and save the file. But i have problems when i make the request because i think of the asyncs nature of node This is the code
var rssUrl = "http://ole.feedsportal.com/c/33068/f/";
var news = {
teamsUrl:{
river: rssUrl + "577741/index.rss",
boca: rssUrl + "577729/index.rss"
},
pathToSaveJson: "../public/ajax/news",
getAll: function(req, res){
for( var i in news.teamsUrl){
var teamName = i;
//console.log(teamName);
console.log(news.teamsUrl[i]);
request(news.teamsUrl[i] , function(error, response, body){
console.log(news.teamsUrl[i]);
parseString(body, function (err, result) {
//console.log(teamName);
var items = result.rss.channel[0].item;
news.saveJson(items, teamName, res);
});
});
}
},
saveJson: function(items, teamName, res){
//console.log(teamName);
var objToSave = [];
items.forEach(function(value, index){
// Clean descriptions , delete tags html
var cleanDescription = value.description[0].split("<")[0];
var link = value.guid[0]["_"];
objToSave.push({
title: value.title[0],
description: cleanDescription,
link: link
})
});
fs.writeFile(news.pathToSaveJson + "/" + teamName +".json", JSON.stringify(objToSave) , function(err){
if(err) console.log(err);
console.log("saved filed");
});
}
}
The first response of console log in the method getAll responds different( works fine) but when i am in the request repeat two times the first and creat only one json file . Any idea?