0

I have a function that should read a JSON file and update this file (writeFile). When I call this function 2 times or more it doesn't update my file and after the 1st call it's adding 1/2 curling brackets at the end of my JSON file. Here is my function:

var fs = require('fs');

function updateJson(ticker, value) {
    //var stocksJson = JSON.parse(fs.readFileSync("stocktest.json"));
    fs.readFile('stocktest.json', function(error, file) {
        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) {
                                console.log("File successfully written");
                            }
                            if (err) {
                                console.error(err);
                            }

                       });
        }
        else {
            console.log(ticker + " doesn't exist on the json");
        }
    });
} // end of updateJson

updateJson("IBM", 77);
updateJson("AAPL", 88);

This is my original JSON file (before this function was executed):

{
    "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": 0,
        "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": 0,
        "prod": "search, android, glass, drive, code school"
    }
}

This is the the part where i'm using the updateJson function:

MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){

    console.log("Connection is opened to : " + "mongodb://" + host + ":" + port + "/" + dbName);

    var q = async.queue(function (doc, callback) {
  // code for your update

            var stockName = doc.ticker;
            var stockValue =  doc.value;

            var yUrl = "http://finance.yahoo.com/q/ks?s=" + stockName;
            console.log("The url is : " + yUrl);
            getStockValue(stockName, yUrl, callback, db);
            // insert here the update of the json
            updateJson(stockName, stockValue);
    }, Infinity);

var cursor = db.collection(requiredCollection).find();
cursor.each(function(err, doc) {
  if (err) throw err;
  if(doc!=null) {
  q.push(doc); // dispatching doc to async.queue
} 
});

q.drain = function() {
  if (cursor.isClosed()) {
    console.log('all items have been processed');
    db.close();
  }
}

 }); // end of connection to MongoClien

1 Answer 1

3

You need to add a callback to your updateJson function, so that

updateJson("IBM", 77);
updateJson("AAPL", 88);

turns into:

updateJson("IBM", 77, function() {
    updateJson("AAPL", 88);
});

function updateJson(ticker, value, callback) {
    //var stocksJson = JSON.parse(fs.readFileSync("stocktest.json"));
    fs.readFile('stocktest.json', function(error, file) {
        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) {
                                console.log("File successfully written");
                            }
                            if (err) {
                                console.error(err);
                            }
                            callback();

                       });
        }
        else {
            console.log(ticker + " doesn't exist on the json");
        }
    });
} // end of updaJson

I recommend using the async library for this: https://github.com/caolan/async#eachSeries

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) {
            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) {
                                callback(err);
                            }

                       });
        }
        else {
            callback(ticker + " doesn't exist on the json");
        }
    });
} // end of updaJson

async.eachSeries([
  {ticker:"IBM", value:77},
  {ticker:"AAPL", value:88}
], updateJson, function(err, success) {
  console.log(err, success);
});
Sign up to request clarification or add additional context in comments.

9 Comments

I've tried the first option and i'm getting this error: callback(); TypeError: undefined is not a function
That's because the second function call (updateJson("AAPL", 88);) is not passing a callback. Try this: updateJson("AAPL", 88, function() { console.log('hey it worked'); });
Ok the 2nd one is working, lets say that i don't know how many times i'll need to call this function it depends on my other functions, because i'm getting some live data from some server , there is any option to call this function in a different way, i mean i don't know if it will be 5 / 10 / 15 times so i can't write it like this ..
Use this library. github.com/caolan/async. You're interested in the "series" method
I can't see the example that you wrote for eachSeries
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.