简体   繁体   English

在node.js中异步读写文件

[英]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 ? 我想知道是否有更好的实施方法?

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 例如,我编写了一个小的getCache函数,该函数首先检查文件是否存在,然后尝试读取该文件并随后触发回调

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) 请注意,在这里,您需要做的是在读取文件并通过if (!error)检查之后写入文件if (!error)

i hope this helps 我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM