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");
我想知道是否有更好的方法來實現?
比方說,我想運行我的功能幾次這意味着它會讀取寫入它,然後它會再次發生的文件,所以我試過這個,並在第二次調用它不寫入文件.. 任何想法爲什麼? – user3502786 2014-09-06 15:24:03
是因爲這個函數檢查文件是否存在第一..如果你想保持改寫只是刪除檢查 – AhmadAssaf 2014-09-06 15:26:17
你說的是我的功能? 如果是我應該刪除哪一行? – user3502786 2014-09-06 15:29:23