There is a code for checking the existence of the user, which is executed but, if the user exists, he should issue a "user exists" to the console and stop the program.

Instead, the program is executed and a new user is written to JSON (a duplicate is created) and three entries are created:

enter image description here

Here is the code itself:

app.use("/register", function (request, response) { console.log(request.body); fs.readFile("./data/users/users.json", "utf-8", function (err, text) { if (err) { console.log("ERROR READING FILE" + err); } else { var users = JSON.parse(text); for (var i = 0; i < users.length; i++) { if (users[i].email === request.body.email) { console.log("user already exists"); break; } else { users.push(request.body); fs.writeFile("./data/users/users.json", JSON.stringify(users), function () { // write new user to json }); } } } }); }); 

Can someone have an example of a registration / authorization form with checks on Angular & Express?

  • You yourself wrote the addition of a new record in the loop! Here it is added several times. - Pavel Mayorov
  • What should your algorithm do if request.body.email matches not users[0].email , but users[1].email ? - Grundy
  • why not use return; ? - Insider
  • @Insider, because if the coincidence is with the second element, and not with the first one, this user will be easily added to the first iteration of the loop - Grundy
  • blame, correct. :) - Michael

1 answer 1

You add a user until a match is found in the file. From this and duplication.

It is necessary to check the presence and or absence of the user, and on the basis of this, to make a decision about the recording:

 var user_in_db = false; for (var i = 0; i < users.length; i++) { if (users[i].email === request.body.email) { console.log("user already exists"); user_in_db = true; break; } } if(!user_in_db){ users.push(request.body); fs.writeFile("./data/users/users.json", JSON.stringify(users), function () { /*write new user to json*/ }); }