我試圖使用節點從循環數據 例如,在loop.json寫入/ JSON文件中使用的node.js
var jsonfile = require('jsonfile');
for (i=0; i <11 ; i++){
jsonfile.writeFile('loop.json', "id :" + i + " square :" + i*i);
}
輸出是
id :1 square : 1
,但我寫的JSON文件添加數據想要這樣的輸出文件(下面),如果我再次運行該代碼,它應該添加新的輸出作爲元素在相同的現有JSON文件中
{
"table": [
{
"Id ": 1,
"square ": 1
},
{
"Id ": 2,
"square ": 3
},
{
"Id ": 3,
"square ": 9
},
{
"Id ": 4,
"square ": 16
},
{
"Id ": 5,
"square ": 25
},
{
"Id ": 6,
"square ": 36
},
{
"Id ": 7,
"square ": 49
},
{
"Id ": 8,
"square ": 64
},
{
"Id ": 9,
"square ": 81
},
{
"Id ": 10,
"square ": 100
}
]
}
我想用我創建的第一個時間同一個文件,但每當我運行代碼的新元素應該添加在同一文件
var fs = require('fs');
var obj = {
table: []
};
fs.exists('myjsonfile.json', function(exists){
if(exists){
console.log("yes file exists");
fs.readFile('myjsonfile.json', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data);
for (i=0; i<5 ; i++){
obj.table.push({id: i, square:i*i});
}
var json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}});
} else {
console.log("file not exists")
for (i=0; i<5 ; i++){
obj.table.push({id: i, square:i*i});
}
var json = JSON.stringify(obj);
fs.writeFile('myjsonfile.json', json);
}
});
感謝回覆 我試過它的工作,但如何檢查舊文件是否存在,然後運行readlfile代碼 else run writeFile直接 我正在創造每日新的當前日期的文件名爲 ,並且我希望在此代碼運行時整天添加新數據 – Isoftmaster
根據您的新問題更新我的答案 – kailniris
再次感謝您 我讓我的代碼工作:D with all您的支持 但我用fs.exists函數 我的問題更新與答案 – Isoftmaster