Ad

File Iteration To Search For Similar Phrases In Node.js

- 1 answer

I have specific issue:

This function is responsible for reading file.

function readFile (email){
  fs.readFile('./files/data.json', 'utf8', (err, fileContents) => {
    if (err) {
      console.error(err)
      return
    }
    try {
      const data = fileContents
      console.log(data)
    } catch(err) {
      console.error(err)
    }
  })
    if(email = (how can iterate file in search of phrases?){
      console.log('identic')
    }
    else{
      console.log('ok')
    }
}

Also I getting request from client with email i pass this parameter to function as email

The structure of file is:

{"username":"test","email":"[email protected]"}
{"username":"test","email":"[email protected]"}

How can I iterate over the data.json file to search for a phrase identical to the parameter being passed? - Need to avoid adding the same data to the file again.

Ad

Answer

You can iterate line by line and using callbacks, return true or false to indicate if the email exist or not. (The best approach is using a database or even bash commands to do this task but here is my solution for Node.js)

'use strict';

const fs = require('fs');
const lineReader = require('readline').createInterface({
  input: fs.createReadStream('./data.txt'),
});

/**
 * Check if a given email exist or not inside data.txt file
 * @param {String} email
 * @param {Function} callback
 * @returns {Object<error, emailIsDuplicated>}
 */
function existEmail(email, callback) {
  let callbackWasExecuted = false;

  lineReader.on('line', async (line) => {
    try {
      const jsonLine = JSON.parse(line);
      if (email === jsonLine.email) {
        callbackWasExecuted = true;
        return callback(null, true);
      }
    } catch (e) {
      callbackWasExecuted = true;
      return callback(new Error(`Error parsing to json next line: ${line}`));
    }
  });

  lineReader.on('close', () => callbackWasExecuted === false && callback(null, false));
}

existEmail('[email protected]', (error, exist) => {
  if (error) {
    return console.error(error);
  }

  console.log(`Result exist email: ${exist}`);
});

Content for data.txt:

{"username":"test","email":"[email protected]"}
{"username":"test","email":"[email protected]"}

Hope it helps. If something about the solution is not clear, let me know.

Ad
source: stackoverflow.com
Ad