hey i want to ask a question, how i can save my data in a json file, i want to see a passwords & usernames my users, i try added but my json file save for a 1 user data only, i want to add a all users.
js
var newusername = req.body.newusername;
newpassword = req.body.newpassword;
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
cap_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
allchars = letters cap_letters numbers ['_'];
goodusername = true;
for(let i of newusername){
if(!allchars.includes(i)){
goodusername = false;
}
}
if(goodusername){
db.list().then(keys => {
if(keys.includes(newusername)){
res.send("Username taken. ");
} else if(newusername == ""){
res.send("Please enter a username.");
} else if(newpassword == ""){
res.send("Please enter a password.")
} else{
db.set(newusername, newpassword).then(() => console.log(`New Account Created Username : ${newusername} || Pass : ${newpassword}`));
//////////////////////////////////// json code ///////////////////////////////////////
fs.writeFile('account.json', newusername, finished);
function finished(err){
console.log('all set.')
}
/////////////////////////////////////////////////////////////////////////////////////
res.cookie("loggedIn", "true")
res.cookie("username", newusername);
res.redirect("/");
}
});
} else{
res.send("Username can only contain alphanumeric characters and underscores.")
}
});```
CodePudding user response:
The issue is that every time you call writeFile
, the previous content of the file is obliterated.
The function you’re looking for is fs.appendFile
// Overwrite file contents
fs.writeFile('account.json', newusername, finished);
// Add to file contents
fs.appendFile('account.json', newusername, finished);
Edit: Bonus tip
Here’s a nice way to setup the arrays of characters and numbers. Lowercase in this example:
const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];