2014-09-05 57 views
0

我有一個應讀取JSON文件並更新此文件(writeFile)的函數。 當我調用這個函數2次或更多時,它不會更新我的文件,並且在第一次調用之後,它將在我的JSON文件的末尾添加1/2個曲形括號。 這裏是我的功能:使用node.js讀取和寫入文件(JSON)

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

這是我原來的JSON文件(被執行該功能前):

{ 
    "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" 
    } 
} 

這是在那裏我使用updateJson功能部分:

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 

回答

3

您需要爲您的updateJson功能添加回調,以便

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

變爲:

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 

我推薦使用異步庫這樣的: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); 
}); 
+0

我嘗試了第一個選項,我」 m得到這個錯誤: 回調( ); TypeError:undefined不是函數 – user3502786 2014-09-05 16:49:11

+0

這是因爲第二個函數調用('updateJson(「AAPL」,88);')沒有傳遞迴調。試試這個:'updateJson(「AAPL」,88,function(){console.log('hey it worked');});' – 2014-09-05 16:51:01

+0

好吧,第二個工作,讓我說我不知道​​多少次我需要調用這個函數,這取決於我的其他功能,因爲我從一些服務器獲取一些實時數據,有任何選擇以不同的方式調用此函數,我的意思是我不知道它是否會是5/10/15倍,所以我不能這樣寫。 – user3502786 2014-09-05 17:07:00