Get data from MySQL database and pass it to jade an access it using nodejs

I have started nodejs to make a simple chat application in it. For this I want to access all users which are in mysql database.

My code is like:

JS

exports.authenticate = function(req, res) {

    //connection.connect();
    var sql="SELECT * from users where username='"+req.body.user+"' and password='"+req.body.pass+"' LIMIT 1";
    connection.query(sql, function(err, rows, fields) {
        if (err) throw err;

        //res.send('Your data is: ', rows);
        var str="Hi, <b>"+rows[0].name+"</b> ("+rows[0].email+")";

        sql="SELECT DISTINCT username,name from users ORDER BY name";
        connection.query(sql, function(err, datarows, fields) {
            if (err) throw err;
            //res.send('Your data is: ', rows+' <br/> All Users are : ', datarows.length+"<a href='/'>Login</a>");
            str+='<ul style="list-style:none;width:300px">';
            for(var index=0;index<datarows.length;index++)
            {
                str+="<li><a href='javascript:;'>"+datarows[index].name+", "+datarows[index].email+"</a></li>";
            }
            str+='</ul>';console.log(str);  
            console.log(str)//gives ul  
        });

        str+="<a href='/'>Login</a>";
        res.send(str);//this not gives the ul of other users
    });

}

The above code has problems that I wrote console.log(str)//gives ul this prints the whole string like Hi, <b>Rohan</b> ("rohan@xyz.com")<ul><li><a>Something</a></li>....</ul>. But res.send(str); sends only Hi, <b>Rohan</b> ("rohan@xyz.com")<a href='/'>Login</a>.

  1. Why this is happening?
  2. Is my str variable not global?
  3. Can I use res.send() many times, if yes then how?

Can I use the above code with jade then what code should I write for this.

I found this answer How to pass data form mongodb into nodejs view (jade)? related to my problem

app.get('/', function(req, res) {
  mgs(dbColl).find(function(data){
    res.render('yourview.jade', { data: data });
  });
});

Then,How to access data in yourview.jade

I also want to know for which type of applications we should use nodejs ?

Thank in advance.

  1. This is happening because Node is asynchronous. Your res.send(str) is executed immediately after calling your inner connection.query(), therefore the callback which adds more hasn't executed before the send.
  2. No, your str variable is not global.
  3. I do not believe so. If you want to write to the response before sending it, you can use res.write().

Yes you can use Jade instead of what you're doing now. Take a look at the Jade docs. They are full of examples of variables being used in jade. To summarize it for you though, you should be able to access a variable with #{variable}.

As for your last question, I'm really not sure what you're asking. You can use node for alot of stuff, from controlling quadcopters to web sites and services.