I have a function that is reading my json File then it should write (update) one field there and change the original file, this is done if the key is existing in the json file. The thing is that i'm inserting multiple objects at once, if of the objects is not located in the json file my function is not doing anything (not updating the file). Here is my Json file:
{
"NVDA": {
"name": "Nvidia Corporation",
"symbol": "NVDA",
"logo": "nvidia.png",
"price": 0,
"prod": "Nvidia Corporation, gforce, g-force, shield"
},
"AAPL": {
"name": "Apple inc",
"symbol": "AAPL",
"logo": "apple.png",
"price": 2,
"prod": "Apple inc, mac, macbook, iphone, ipod, ipad, osx"
},
"GOOG": {
"name": "Google inc",
"symbol": "GOOG",
"logo": "google.png",
"price": 0,
"prod": "search, android, glass, drive, code school"
},
"IBM": {
"name": "ibm",
"symbol": "ibm",
"logo": "google.png",
"price": 1,
"prod": "search, android, glass, drive, code school"
}
}
This is my function:
function updateJson(data, callback) {
var ticker = data.ticker;
var value = data.value;
//var stocksJson = JSON.parse(fs.readFileSync("stocktest.json"));
fs.readFile('stocktest.json', function(error, file) {
if (error) {
console.error(error);
callback(error);
}
var stocksJson = JSON.parse(file);
if (stocksJson[ticker]!=null) {
console.log(ticker+" price : " + stocksJson[ticker].price);
console.log("changing the value...")
stocksJson[ticker].price = value;
console.log("Price after the change has been made -- " + stocksJson[ticker].price);
console.log("printing the the Json.stringify")
console.log(JSON.stringify(stocksJson, null, 4));
fs.writeFile('stocktest.json',JSON.stringify(stocksJson, null, 4) , function(err) {
if(!err) {
callback(null, "File successfully written");
}
if (err) {
console.error(err);
callback(err);
}
}); // end of writeFile
}
else {
console.log(ticker + " not in the json");
callback(ticker + " doesn't exist on the json");
}
}); // end of readFile
} // end of updaJson
var arr = [];
arr.push({ticker:"IB", value:1});
arr.push({ticker:"AAPL", value:2});
console.log("printinhg the array.....")
for(var i=0; i<arr.length; i++) {
console.log(arr[i]);
}
async.eachSeries(arr, updateJson, function(err, success) {
console.log('All items have been updated');
});