2015-07-13 87 views
0

我只是想在調用某個函數後將json對象寫入文件(不一定是.json文件)。當用另一個json對象調用該函數時,我想將該對象追加到文件中。將json對象附加到nodejs文件中

目前我正在使用jsonfile

var jsonfile = require('jsonfile'); 
... 
users_file = "./users_file"; 
function update(user_json) { 
    jsonfile.writeFile(users_file,user_json), function(err) { 
     console.error(err); 
    }); 
} 

但用另一個json對象再次調用更新,第一行將被覆蓋。

例如:

json1 = {"id":123456,"first_name":"John","last_name":"Smith","username":"johnsmith"} 
json2 = {"id":654321,"first_name":"marc","last_name":"cold","username":"marccold"} 
調用 update(json1)後來 update(json2)

我想要的文件看起來像這樣:

{"id":123456,"first_name":"John","last_name":"Smith","username":"johnsmith"} 
{"id":654321,"first_name":"marc","last_name":"cold","username":"marccold"} 

目前第二線替換第一行。我試着先讀取文件,然後連接兩個json對象,但失敗了。當文件爲空時也需要工作。

+2

嘗試使用函數appendFile()代替writeFile() – binariedMe

+0

謝謝。如果需要,您可以將其添加爲答案。 – Sadik

回答

1

使用appendFile()代替writeFile()。 writeFile()將寫入新文件或覆蓋現有文件(如果有的話)。雖然appendFile()是將內容附加到現有文件(如果有的話)或創建一個新文件並添加內容。

相關問題