Alex Brodov
Alex Brodov

Reputation: 3515

Reading and Writing files async in node.js

Currently i'm reading and writing files asynchronously, the thing is that i'm not sure that all the line from the file were read before the rest of my code is executed, here is my code:

var fs = require('fs');

//var str = fs.readFileSync("stockststs.json");



function updateJson(ticker) {
    //var stocksJson = JSON.parse(fs.readFileSync("stocktest.json"));
    fs.readFile('stocktest.json', function(error, file) {
        stocksJson =  JSON.parse(file);



        if (stocksJson[ticker]!=null) {
            console.log(ticker+" price : " + stocksJson[ticker].price);
            console.log("changin the value...")
            stocksJson[ticker].price =  989898;
            console.log("Price after the change has been made -- " + stocksJson[ticker].price);
             fs.writeFile('stocktest.json',JSON.stringify(stocksJson, null, 4) , function(err) {  
                            if(!err) {
                                console.log("File successfully written");
                            }


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


updateJson("APPL");

I'm wondering if there is any better way to to implement ?

Upvotes: 0

Views: 2602

Answers (1)

AhmadAssaf
AhmadAssaf

Reputation: 3664

its always a good practice to check in your callback for error. For example, i have written a small getCache function that checks if the file exists first, then tries to read that file and fire a callback afterwards

Cache.prototype.getCache = function(cache_filename, callback) {
    cache_filename = this.cache_foldername + cache_filename;
    fs.exists(cache_filename, function(exists) {
        if (exists) {
            fs.readFile(cache_filename, 'utf8', function (error, data) {
                if (!error) {
                    console.log('File: '+ cache_filename +' successfully Read from Cache!');
                    _.isObject(data) ? callback(null,data) : callback(null,JSON.parse(data));
                } else console.log("Error Reading Cache from file: " + cache_filename + " with Error: " + error);
            });
        } else callback(null,false);
    });
}

note that in here what you need to do is to write the file after it has been read and checked with the if (!error)

i hope this helps

Upvotes: 1

Related Questions