[英]Node.js - FileSystem.writeFile returning badly formatted JSON
所以這里的前提是一個 JavaScript 腳本,除其他外,它應該維護一個小“字典”作為本地 JSON 文件,其中一些用戶定義的字符串可以映射到一個鍵(一個字符串)並序列化。 該腳本恰好已經依賴於Node.js的,我並不想在瀏覽器中運行反正這一點,這就是為什么我如何使用Node.js的文件系統庫。 問題是當我嘗試使用下面的函數將新定義保存到這本詞典時。
(另請注意,僅僅因為在調用此函數的包裝函數中如何處理數據,參數作為字符串數組傳遞,而不僅僅是簡單的“鍵”和“值”字符串。這是有意的。 )
var sDictFile = "dict.json";
async function com_setdef(args){
if (args.length > 1) {
let sJSONKey = args[0];
let sDef = args.slice(1).join(" ");
fs.readFile(sDictFile, "utf8", (err, data) => {
if (err) throw err;
let pDict = JSON.parse(JSON.stringify(data));
if (pDict.hasOwnProperty(sJSONKey)) { // this entry already exists in the dictionary, so just edit it
let pRow = pDict.sJSONKey;
if (pRow.locked == true) {
return "This dictionary entry is locked. Its definition cannot be changed unless it is unlocked, which can only be done by an admin.";
} else {
pRow.def = sDef;
fs.writeFile(sDictFile, JSON.stringify(pDict, null, 2), err => {
if (err) throw err ;
});
}
} else { // this entry doesn't exist yet, so create it from scratch
let sJSONValue = {"def":sDef,"locked":false,"viewlocked":false};
pDict[sJSONKey] = sJSONValue;
fs.writeFile(sDictFile, JSON.stringify(pDict, null, 2), err => {
if (err) throw err ;
});
return "completed";
}
});
}
}
只是為了給它一些要加載的數據,我把它放在其他空的 dict.json 中:
{
"A": {
"def": "the first letter in the alphabet",
"locked": false,
"viewlocked": false
}
}
當這個函數第一次使用參數com_setdef( ["cedar", "a", "species", "of", "tree"] )
被調用時,之前為空的 dict.json 現在看起來像這樣:
"{\r\n\t\"A\": {\r\n\t\t\"def\": \"the first letter in the alphabet\",\r\n\t\t\"locked\": false,\r\n\t\t\"viewlocked\": false\r\n\t}\r\n}"
所以它不僅沒有保存任何新數據,我也不知道所有這些其他垃圾是從哪里來的。 FileSystem.readFile 的 Node.js 文檔說,如果沒有指定編碼,則返回原始緩沖區,所以我懷疑這就是這個,但即使指定了 UTF-8,它仍然用一個一堆我沒有明確傳遞給它的垃圾。
還有一些額外的壞消息 - 它永遠不會返回字符串“已完成”。 整個函數在等待從該函數返回的字符串的異步包裝函數中調用,因此它可以比較它的長度並確保它 > 0 和str.length > 0
。 相反,我得到: (node:89944) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined
。 所有這一切使它看起來像 fs.readFile,根據文檔的異步進程,從未真正終止。 我認為。
所以我顯然不知道我在做什么。 為什么腳本在向 JSON 文件中添加新行並保存時如此失敗?
您的問題是從fs.readfile()
返回的data
已經是一個字符串。 因此,當您執行JSON.parse(JSON.stringify(data))
- 您實際上首先將字符串字符串化,然后解析字符串化的字符串會給您一個字符串(因此所有這些煩人的\\r\\n
)。
查看它的一種方法是在您的代碼中添加console.log(typeof pDict)
它將打印string
。
解決方案:確保您的dict.json
是格式良好的 JSON,然后更改為JSON.parse(data)
(即沒有JSON.stringify()
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.