Home > Software engineering >  how do I exit (return) from a function inside a another function
how do I exit (return) from a function inside a another function

Time:12-27

i made this to save a some info on a file and to read line by line using readline node module

there is two res.send() one is with return . it only return within current function its sitting on . How do i completely exit from then functions?

this just for a test . I know I should use Databases

router.post('/login', (req, res) => {

    console.log(req.body);
    var lineReader = require('readline').createInterface({
        input: require('fs').createReadStream('./users.txt')
    });

    lineReader.on('line', function (line) {
        const lineJson = JSON.parse(line);

        if (lineJson["username"] == req.body.username) {
            if (lineJson["password"] == req.body.password) {


                return res.send({ msg: "matched" });
            }
        }
    })

res.send({msg:"not matched"});
})

simplified

function(){
    function(){

        return...
    }
}

CodePudding user response:

Your problem is related to your experience with the asynchronous nature of nodejs.

You need to use the line-reader in async mode for your tests:

lineReader.eachLine('file.txt', function(line, last, cb) {
  console.log(line);

  if (/* done */) {
    cb(false); // stop reading
  } else {
    cb();
  }
});

Or just read the entire file and then query it as if it was a sql table:

var table = //some asyn read of file

if(user-password match){
  return res.send({ msg: "matched" });
}else{
  return res.send({msg:"not matched"});
}

You can also read the file in async mode (which is better) and in the callback execute your express logic

  • Related