我想為每個訪問該站點的用戶制作 json 檔案。我正在使用帶有 EJS 模板的 NodeJS express Js。我不想使用 mongoDB。我想使用 json 檔案作為資料庫。當用戶訪問網站并填寫表格時。表單資料將存盤在 json 檔案中。每個訪問該站點的新用戶都會創建一個新的 json 檔案來存盤該特定用戶的資料。任何人都可以這樣做嗎?我不知道如何使用 cookie 和 session。
uj5u.com熱心網友回復:
如果不是敏感資料,cookie-parser是一種使用 cookie 的簡單方法。否則,不能推薦足夠的 DBMS。
無論如何,要回答這個問題,除了將 fs 包與writeFile、readFile一起使用并管理要用作資料庫的物件之外,您無需做更多的事情。
這是一個使用物件陣列作為資料庫的簡單示例,使用fs/promises 包,該包用 promise 包裝 fs 方法。
PS。您可能希望使用更好的結構來避免 de O(n) 復雜性,例如每個用戶一個單獨的檔案。另外,對同一個檔案的并發訪問是不安全的,請查看writeFile的檔案
const fs = require('fs/promises');
const fileName = 'db.json';
let data = [{
name: 'John Doe',
age: 42,
},
{
name: 'Jane Doe',
age: 39,
}
];
async function main() {
await fs.writeFile(fileName, JSON.stringify(data)); // first version of file, not really needed
let rawData = await fs.readFile(fileName); // read file, result is still an string
data = JSON.parse(rawData); // parse the data read to an object
let index = data.findIndex((item) => item.name === 'John Doe'); // find index of John Doe in the array
data[index].age = 43; // update age of John Doe
await fs.writeFile(fileName, JSON.stringify(data)); // write back to file
console.log(data);
}
main();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/508514.html
