【问题标题】:Reading and Writing files async in node.js在 node.js 中异步读写文件
【发布时间】:2014-09-01 17:37:59
【问题描述】:

目前我正在异步读取和写入文件,问题是我不确定在执行其余代码之前是否已读取文件中的所有行,这是我的代码:

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");

我想知道是否有更好的方法来实现?

【问题讨论】:

    标签: javascript node.js asynchronous


    【解决方案1】:

    检查回调是否有错误总是一个好习惯。例如,我编写了一个小的 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);
        });
    }
    

    请注意,在这里您需要做的是在读取并使用if (!error)检查文件后写入文件

    希望对你有帮助

    【讨论】:

    • 假设我想运行我的函数几次,这意味着它将读取写入它的文件然后它会再次发生,所以我已经尝试过这个并且在第二次调用它不是写入文件..知道为什么吗?
    • 是的,因为这个函数首先检查文件是否存在..如果你想继续重写,只需删除该检查
    • 你是在说我的功能吗?如果是,我应该删除哪一行?
    • 我以为你重用了我的功能。我现在正在用我的手机查看。我会尽快在我的笔记本电脑上回复你
    • 你能分享更新的代码吗..我猜上面的代码已经更新了
    猜你喜欢
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2021-09-10
    • 2016-11-17
    • 2015-12-29
    • 2018-06-04
    • 2017-12-23
    • 1970-01-01
    相关资源
    最近更新 更多