0

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...
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
heyiis
  • 269
  • 2
  • 9
  • What is the error? I think it is working – JRichardsz Dec 26 '21 at 18:13
  • 1
    The problem is, that the outer function might have already returned before the on() handler is even fired. So what you are trying to do here is not possible this way. You might be able to wrap the stream of the lineReader into a Promise and await it from the route handler. – Max Dec 26 '21 at 18:14
  • You cannot return from outer function. What you can do instead is wrap inner function into a Promise that will be resolved at a certain condition, then await for that function's end. In this particular case you also need to process 'close' event (i.e., if username/password is not found). – raina77ow Dec 26 '21 at 18:16
  • on() is sync . Ill try. – heyiis Dec 26 '21 at 18:17

1 Answers1

0

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

JRichardsz
  • 14,356
  • 6
  • 59
  • 94