Search code examples
node.jsreturnfs

NodeJS return not stopping the entire function


I have the function, enter, that contains two fs.readFile functions inside and on the innermost readfile I'm checking to see whether a txt file contains a certain keyword, and if it does it should stop the entire enter function.

Her is what the enter function looks like:

async function enter(email, firstName, lastName){

  fs.readFile(fileName, function(err, data){
    parsedData = JSON.parse(data);

    email = parsedData.email;

    fs.readFile('./anotherfile.txt', function (err, data) {
      if (err) throw err;
      if(data.includes(email)){
        console.log('Stopping function');
        return;
      }
    });
  });

  console.log('Continuing with function');
}

The problem is that when anotherfile.txt contains the keyword, it does not stop the entire function, it continues and logs, "Continuing with function" as seen in the code above.

Any help would be appreciated!


Solution

  • fs promises are available Node v11.0.0 or You can can convert like this const readFile = util.promisify(fs.readFile);

    const fsp = require('fs').promises;
    
    async function enter(email, firstName, lastName) {
    
        try {
            let data = await fsp.readFile(fileName)
            let parsedData = JSON.parse(data);
            let email = parsedData.email;
            data = await fsp.readFile('./anotherfile.txt')
    
            if (data.includes(email)) {
                console.log('Stopping function');
                return;
            }
    
    
            console.log('Continuing with function');
    
    
        } catch (err) {
            throw err
        }
    }