簡體   English   中英

JSON 在 nodejs 應用程序中寫入兩次后文件為空

[英]JSON File empty after writing to it twice in nodejs app

構建一個簡單的筆記程序,您可以在其中添加筆記並將它們存儲到 JSON 文件中,但是每當我寫 2 條筆記時,JSON 文件就會被完全清空。 當我只是使用$ node notes.js執行腳本來測試功能時,這不是問題,只有當我從 npm 應用程序調用它時。

筆記.js

const fs = require("fs"); 
let rawdata = fs.readFileSync('notedb.json');
let notes = JSON.parse(rawdata);

// takes in note, adds it to database
function addnote(note) {
    // format item to prepare for json
    var jsonitem = {
        "note": note
    };

    // add item to the end of json file
    notes.push(jsonitem);

    // write the item
    fs.writeFile("notedb.json", JSON.stringify(notes), err => {
        if (err) console.log("error");
    });

    // reload the notes on the website
    shownotes();
}

function shownotes() {
    // put notes into string
    var notestostring;
    for (i = 0; i < notes.length; i++) {
        notestostring+= notes[i]["note"]
    }
    
    // add to document
    document.getElementById("note-ul").innerHTML = notestostring;
}

筆記.html

<!DOCTYPE html>

<script type="text/javascript" src="notes.js">

<!-- input with script that makes it submit when enter key is hit -->
<input type="text" onkeydown="add(this);" id="note-input">
<script>
   function add(ele) {
       if (event.keyCode == 13) {
           addnote(ele.value);
           var form = document.getElementById("note-input");
       }
   }
</script>

我添加第一個注釋,它會毫無問題地添加到 JSON 文件中,然后添加第二個注釋,整個文件將為空

(注意:我將代碼縮短為僅包含重要元素,忽略語法錯誤)

最終放棄了這個問題,轉而使用一個 CSV 文件作為存儲。 我認為它與異步寫入/解析有關,但由於我對 javascript 比較陌生,所以我不確定異步處理是如何工作的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM