iam trying to verify multiple email addresses from txt file and then save valid emails to another txt file using nodejs. but it didn’t work. the file has been read and it gives invalid to all emails even some of them are valid emails.
here is my code
const fs = require("fs");
function validateEmail(email) {
const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/;
return emailRegex.test(email);
}
const inputData = fs.readFileSync("./input.txt", "utf8");
const emailAddresses = inputData.split("/n");
const validEmails = [];
for (const email of emailAddresses) {
const isValid = validateEmail(email);
if (isValid) {
validEmails.push(email);
}
console.log(`${email}: ${isValid ? "valid" : "invalid"}`);
}
fs.writeFileSync("valid-emails.txt", validEmails.join("n"), "utf8");
console.log(`Valid email addresses saved to "valid-emails.txt".`);
i tried to verify emails from txt file using regular expression. but it gives all of them invalid
2
Answers
Is the problem that you’re splitting on
/n
instead ofn
on line 8 and that because of this, your array contains only one item and it’s the entire content of your input file?Add a console.log(emailAddresses) and that should confirm it for you.
try this way