skip to Main Content

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


  1. Is the problem that you’re splitting on /n instead of n 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.

    Login or Signup to reply.
  2. try this way

    const fs = require("fs");
    
    const inputData = fs.readFileSync("./input.txt", "utf8");
    
    const validEmails = inputData.split("n").filter(email => {
        const re = /^[^s@]+@[^s@]+.[^s@]+$/;
        if (re.test(email)) {
            return email;
        }
    });
    
    fs.writeFileSync("valid-emails.txt", validEmails.join("n"), "utf8");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search