我在 Java 中有一種“json 數據容器”,但我目前在一個 JavaScript 項目中工作,我想像通常在 Java 中那樣保存數據:https ://hastebin.com/arajusubum.cs這是我在 Java 中的“容器”類,我嘗試在 JavaScript 中重新創建它,如下所示:const fs = require("fs");class Container { constructor(path) { this._path = path; this._storage = ""; } put(key, value) { console.log(`${key}: ${value}`); this._storage[key] = value; console.log(this._storage); } get(key) { if(!this._storage.includes(key)) return null; return this._storage[key]; } flush() { const jsonString = JSON.stringify(this._storage); fs.writeFile(this._path, jsonString, 'utf8', function (err) { if (err) { console.log("An error occured while writing JSON Object to File."); return console.log(err); } }); }}module.exports = Container;但它不起作用,這意味著如果我嘗試輸出類對象,它不會引發任何錯誤并且不會發生任何事情。這就是我將它添加到我的代碼中的方式:const Container = require("../classes/Container");......const newContainer = new Container("./test.json");newContainer.put("taskID", "1234");console.log(newContainer);
nodejs創建一個“數據容器”
慕妹3146593
2022-06-09 16:57:04