How I can take/save a js signup to my json file - javascript

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.")
}
});```

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'];

Related

Source of "undefined" showing in console

Javascript beginner here. This function is supposed to show the position of any given letter in the English alphabet. It seems to run fine, but along with the result, I get an undefined error. Where is this coming from?
var alphabet = ['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'];
function position(letter){
letter = letter.toLowerCase();
for (var i = 0; i < alphabet.length; i++) {
if (alphabet[i] === letter){
console.log('Position in the alphabet is: ' + i);
break;
}
}
};
console.log(position("Z"));
Change:
console.log(position("Z"));
to:
position("Z");
Function position does not return anything--that is why you are getting undefined.
You aren't return any values from position(...) function. To fix the undefined error, you might want to return null if no result is found, like the example:
var alphabet = ['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'];
function position(letter){
letter = letter.toLowerCase();
for (var i = 0; i < alphabet.length; i++) {
if (alphabet[i] === letter){
return 'Position in the alphabet is: ' + i;
}
}
return null;
};
console.log(position("Z"));
The undefined you are seeing in the console is not an error at all. Instead, it is the result of the console.log() statement in last line of code, as #Russ mentioned. It is logging what it received after executing position("Z") - which is actually nothing or undefined.
If you wish to be able to use console.log() for the output of your function, you could have it return a string. This would also eliminate the need for a break; statement in your for loop. You might include a "not found" type of default statement as well to protect against an actual error. (#Dorado's null default is a good alternative.) Here's what my suggestion might look like for your code:
var alphabet = ['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'];
function position(letter){
letter = letter.toLowerCase();
for (var i = 0; i < alphabet.length; i++) {
if (alphabet[i] === letter){
return('Position in the alphabet is: ' + i);
}
}
return 'Character not found in the alphabet!';
};
console.log(position("Z"));
This would give you the single console output you desire, remove the undefined from your console, and allow you to use this function in other code.
your function could be simply this:
var alphabet = ['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'];
function position=(letter)=> {
console.log(`Position in the alphabet is: ${alphabet.findIndex(el=>el===letter.toLowerCase())}`)
}
position("Z");

Random generate characters excluding

If I have the code below to generate random characters, how can I code it to generate those same characters excluding some values? I.e. corresponding to var charactExclude.
Ex:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
var charactExclude = document.getelementbyID(character).content.text
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result
}
console.log(makeid(10))
Here's how I would go about this:
First select your element containing the excluded characters (You have some errors in your JS) You can split this into an array using .split('') and use the [...new Set(Your array here)] pattern to remove duplicates at this point.
Then create a new variable for the filtered string, and loop through replacing the characters you do not want to include.
Finally, use this new variable in the creation of your string.
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactExclude = [
// Using a Set efficiently removes duplicates, and will speed up the loop below, and the ... expands them back into an array
...new Set(
// Using split('') will turn the string into an array of characters
document.getElementById("character").innerText.split('')
)
];
// Create a new variable, and then loop through the charactExclude array, removing undesired chars
var charactersFiltered = characters
for (var i = 0; i < charactExclude.length; i++) {
charactersFiltered = charactersFiltered.replace(charactExclude[i], '')
}
for (var i = 0; i < length; i++) {
result += charactersFiltered.charAt(Math.floor(Math.random() * charactersFiltered.length));
}
return result
}
console.log(makeid(100))
<div id="character">ABCDEFG</div>
I admit this might be a little tortuous as solution...
/*
* Char codes ranges:
* 0-9 -> 48-57
* A-Z -> 65-90
* a-z -> 97-122
*/
function makeId(idLength, charsToExclude = []) {
// list of all invalid char codes between '0' (char code 48) and 'z' (char code 122)
const invalidCharCodes = [58, 59, 60, 61, 62, 63, 64, 91, 92, 93, 94, 95, 96];
// add to the invalid char list any char passed as parameter
if (charsToExclude.length > 0) {
charsToExclude.forEach(char => invalidCharCodes.push(char.charCodeAt(0)))
}
let id = '';
while (id.length < idLength) {
let charCode;
do {
charCode = Math.floor(Math.random() * (122 - 48 + 1)) + 48;
} while (invalidCharCodes.indexOf(charCode) >= 0)
id += String.fromCharCode(charCode);
}
return id;
}
// test
console.log('should return an ID containing digits and letters (either lower or upper case):', makeId(10));
console.log('should return an ID containing only digits:', makeId(10, ['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', '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']));
console.log('should return an ID containing only letters (either lower or upper case):', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']));
console.log('should return an ID containing only lower case letters:', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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']));
console.log('should return an ID containing only upper case letters:', makeId(10, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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']));
console.log('should return an ID containing only 0s:', makeId(10, ['1', '2', '3', '4', '5', '6', '7', '8', '9', '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', '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']));
You could use Array.filter for that
const alphabetAndNumbers = () => [...Array(26)]
.map((x, i) => String.fromCharCode(i + 65))
.concat([...Array(26)].map((x, i) => String.fromCharCode(i + 97)))
.concat([...Array(10)].map((x, i) => `${i}`));
console.log(`Your id: ${createRandomId(10)}`);
function createRandomId(len) {
let characters = alphabetAndNumbers();
console.log(`[characters] initial ${characters.join("")}`);
//retrieve characters to exclude from the template element and split it to an array
const excludes = document.querySelector("#excludes").content.textContent.split("");
// filter initial characters array to exclude the characters in [excludes]
// now [characters] is an array too
characters = characters.filter(c => !~excludes.indexOf(c));
console.log(`excluded ${excludes.join("")}`)
console.log(`[characters] now ${characters.join("")}`);
// create an array with length [len], map characters (pseudo random) into it
// and return the joined array
return [...Array(len)]
.map(v => characters[Math.floor(Math.random() * characters.length)])
// ^ characters is array, so you can pick an element from it
.join("");
}
// easier may be to initially use a subset
const createRandomIdSimple = (len, chars) => [...Array(len)]
.map(v => chars[Math.floor(Math.random() * chars.length)])
.join("");
const chars4Id = document.querySelector("#chars4RandomId").content.textContent.split("");;
console.log(`Your id from createRandomSimple: ${createRandomIdSimple(10, chars4Id)}`);
<template id="excludes">DWX23Aal0gn</template>
<template id="chars4RandomId">BCEFGHIJKLMNOPQRSTUVYZbcdefhijkmopqrstuvwxyz1456789</template>
Bonus: rewritten to a factory function for creating random Id's
const randomId = RandomIdFactory();
const log = Logger();
log(`Lets create 25 pseudo random id's of length 32`,
`without "l" (lowercase L) and "0" (zero):\n`,
[...Array(25)].map(x => randomId(32, "l0")).join("\n"));
function RandomIdFactory() {
const characters = [...Array(26)]
.map((x, i) => String.fromCharCode(i + 65))
.concat([...Array(26)].map((x, i) => String.fromCharCode(i + 97)))
.concat([...Array(10)].map((x, i) => `${i}`));
return (len, excludes) => {
const chars = excludes &&
characters.filter(c => !~excludes.indexOf(c)) ||
characters;
return [...Array(len)]
.map(v => chars[Math.floor(Math.random() * chars.length)])
.join("");
};
}
function Logger() {
const logEl = document.querySelector("#log") || (() => {
document.body.append(Object.assign(document.createElement('pre'), {id:"log"}));
return document.querySelector("#log");
})();
return (...strs) => strs.forEach(s => logEl.textContent += `${s}\n`);
}

How do I split an array with 26 different string values, that appear as 1 string on a webpage?

var alphabet = ['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'];
var letters = document.createElement("ul");
letters.innerHTML = alphabet;
// This is to split the array "alphabet" into individual strings
var separatedLetters = document.getElementById("letters");
separatedLetters.appendChild(letters);
this is the code I used to attempt to split the string,
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
and that is how it appeared on my web page, it displays as one whole string instead of each letter being a string.
Something like the follow? Since you are using an unordered list, I am assuming you would want each character on its own bullet
var alphabet = ['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'];
var ul = document.createElement("ul");
for(var i = 0; i < alphabet.length; ++i) {
var li = document.createElement("li");
li.innerText = alphabet[i];
ul.appendChild(li);
}
document.body.appendChild(ul);
Here an example:
var alphabet = ['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'];
var string = alphabet.join("");// <--- array to string ABCDEFGHIJKLMNOPQRSTUVWXYZ
console.log(string);
var alphabet = string.split("");// <--- string to array
console.log(alphabet);
As mentioned, you should wrap every letter with li and append each element to the list.
Additionally, in order not to cause unnecessary reflows, you can utilize Document.createDocumentFragment()
HTML:
<div id="letters"></div>
JS:
var alphabet = ['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'];
var separatedLetters = document.getElementById("letters");
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createElement('ul'));
alphabet.forEach(letter => {
var li = document.createElement('li');
li.textContent = letter;
fragment.childNodes[0].appendChild(li);
});
separatedLetters.appendChild(fragment);

Passing Array Value as Parameter causes undefined [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
My Array:
var alphabet = ['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'];
Set Function to Button:
var alphabet = ['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'];
for (var idx = 0; idx < alphabet.length; idx++) {
var bttn = document.createElement("button");
bttn.innerText = alphabet[idx];
bttn.onclick = function() {
this.disabled = true;
checkIfWordContainLetter(alphabet[idx]);
}
document.getElementById("hangmanContent").appendChild(bttn);
}
function checkIfWordContainLetter(letter) {
alert(wordToGuess);
alert(letter);
}
Causes undefined when I pass alphabet[idx] as parameter but if I pass for example 'a' it alerts a.
Try below code:
var alphabet = ['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'];
for(var idx=0;idx<alphabet.length;idx++)
{
var bttn = document.createElement("button");
bttn.innerText = alphabet[idx];
bttn.onclick = function () {this.disabled=true;
checkIfWordContainLetter(this.innerText);
}
document.getElementById("hangmanContent").appendChild(bttn);
}
function checkIfWordContainLetter(letter)
{
alert(letter);
alert(letter);
}
<body>
<div id="hangmanContent"></div>
</body>
This is a issue related to scopes.
When you click the button, idx is equal to 26, because the for already ended, this index doesn't exists on array.
You can simple correct this changing var idx to let idx, but note that this is implemented only on modern browsers.
A legacy solution could be:
for (var idx = 0; idx < alphabet.length; idx++) {
var bttn = document.createElement("button");
bttn.innerText = alphabet[idx];
bttn.onclick = (function (index) {
return function () {
this.disabled = true;
checkIfWordContainLetter(alphabet[index]);
}
} (idx));
document.getElementById("hangmanContent").appendChild(bttn);
}
Read: JavaScript closure inside loops – simple practical example
Here is solution:
var alphabet = ['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'];
for(var idx=0;idx<alphabet.length;idx++)
{
var bttn = document.createElement("button");
bttn.innerText = alphabet[idx];
bttn.onclick = function (idx)
{
this.disabled=true;
checkIfWordContainLetter(alphabet[idx]);
}.bind(this, idx);
document.getElementById("hangmanContent").appendChild(bttn);
}
function checkIfWordContainLetter(button)
{
//alert(wordToGuess);
alert(button.innerText);
}
You should understand javaScript closure.
When you clicked one of those buttons, the event handler will be excuted. You exposed the idx in the checkIfWordContainLetter(alphabet[idx]) to be 1,2,3,4,.....However, it will always be (alphabet.length + 1). They all refer to the same place in memory.

JavaScript: Why This Code Doesn't Work?

I am trying to create an text encrypter, but when i entered this code, nothing happens. What is wrong with my code?
function Encrypt(txt) {
var chars = {'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'}
for (i = 0; i < txt.length; i++) {
var chr = txt.charAt(i);
var pos = chars.indexOf(chr);
if (pos == chars.length) {
pos = 0;
}
else {
pos = pos++
}
txt.charAt(i) = chars[pos];
}
alert(txt);
}
You need
array [] instead of object {},
some declared variables
an empty result string newText, a string is read only with the character access
a valid check if the letter is not in the array
increment pos without assignment.
append the result string with the encoded character
function Encrypt(txt) {
var chars = ['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'],
i, newText = '', chr, pos;
for (i = 0; i < txt.length; i++) {
chr = txt[i];
pos = chars.indexOf(chr);
if (!~pos) {
pos = 0;
} else {
pos++;
}
newText += chars[pos];
}
document.write(newText);
}
Encrypt('test');
Because this is not an array, but object... and object has to have "index" : "value" structure.
Change this:
var chars = {'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'}
to this:
var chars = ['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']
Not considering the errors well described in the other answers, my proposal to encrypt a string is:
function Encrypt(txt) {
var chars = ['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'];
var txtResult = txt.split('').map(function(val) {
var pos = chars.indexOf(val);
return chars[(pos == chars.length) ? 0 : (pos + 1)];
}).join('');
document.write(txtResult);
}
Encrypt('gaemaf');

Categories

Resources