3

I am working on really simple node.js projects to better understand its callback functioning.

Suppose I have a login "system" like this one here:

if( req.query["username"] == "john" && req.query["password"] == "smith" )   {
    req.session.gatekeeper = req.query["username"];
    res.end( "succesfully logged in" );
} else { res.end( "wrong username or password" ); }

so far, so easy. Now suppose that instead of simply having "john:smith", I'd have it stored on redis. With PHP I'd have done it this way:

if( $r->get("$usernameIn") == $passwordIn ) {
  $_SESSION['gatekeeper'] = $usernameIn;
  echo "succesfully logged in";
}

but now, by having a look at the redis documentation (https://github.com/mranney/node_redis/) for node, I see that the get command is like this:

client.get("foo", function(err, reply) {
    console.log(reply);
});

It is really complicated for me to understand how to "structure" the first code I provided with this last one.

Any help? Thanks in advance.

john smith
  • 565
  • 1
  • 10
  • 20

1 Answers1

2

Nearly everything in node.js is asynchronous. So, nearly every method that is called, you must specify a callback method to handle the result of the method call. Normally, the callback function takes two parameters: error, result. So it is up to you to check for the error and then handle the result. There are other node modules that will allow for cleaner code (node promises), but that is out of scope for your question.

As a disclaimer I have not used redis before, so my code example below is based on your code example from above and a quick overview of the redis node.js module.

var redis = require("redis"),
    client = redis.createClient();

client.on("connect", function () {
    client.get(userName, function(err,returnedPassword){

      if(password === returnedPassword) {
        req.session.gatekeeper = req.query["username"];
        res.end( "succesfully logged in" );
      } else {
        res.end( "wrong username or password" );
      }
   });
});
pgreen2
  • 3,601
  • 3
  • 32
  • 59
  • cool, thank you! it's still a bit hard to mentally enter in this async state, coming from php. anyway, you should have a look at redis, it goes like bread and butter with node.js – john smith Dec 09 '12 at 18:46
  • Personally, I think the callbacks are a little difficult to read when you have multiple in a row. I really like promises. I normally use https://github.com/kriszyp/node-promise. Here is a link of stackoverflow people talking about them: http://stackoverflow.com/questions/4296505/understanding-promises-in-node-js – pgreen2 Dec 10 '12 at 12:26