Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do I exit (return) from a function inside a another function

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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...
    }
}

>Solution :

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 the 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading