2014-09-01 76 views
0

我目前正在讀和異步寫入文件,事情是,我不知道那是執行我的代碼的其餘部分之前全部來自該文件的行中讀取,在這裏是我的代碼:讀取和寫入文件異步在node.js中

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

我想知道是否有更好的方法來實現?

回答

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)

檢查後,我希望這有助於

+0

比方說,我想運行我的功能幾次這意味着它會讀取寫入它,然後它會再次發生的文件,所以我試過這個,並在第二次調用它不寫入文件.. 任何想法爲什麼? – user3502786 2014-09-06 15:24:03

+0

是因爲這個函數檢查文件是否存在第一..如果你想保持改寫只是刪除檢查 – AhmadAssaf 2014-09-06 15:26:17

+0

你說的是我的功能? 如果是我應該刪除哪一行? – user3502786 2014-09-06 15:29:23