Puneet Kala
Puneet Kala

Reputation: 3

Nodejs Printing Issue

This is my app.js file

var http =  require('http');
var url = require('url');
var mysql = require('mysql');
var requestListener = function(request, response){
var urlParse = url.parse(request.url,true);
var path = urlParse.pathname;
var query = urlParse.query;
var jsonString;
if(path === "/getArticleById"){
    var conn = mysql.createConnection({
        host:'localhost',
        port:'3306',
        user:'root',
        password:'root123',
        database:'food' 
    });
    conn.connect(function(err){
        if(err){
            console.log('Error connecting to database');
            return;
        }
        response.writeHead(200, {'Content-Type': 'text/plain' });
    });
    var id = query.id;
    conn.query('select * from article where id=?', id,function(err,rows){
      if(err){
          console.log(err);
      }

      jsonString = rows;
    });
    conn.end();
    console.log(jsonString);
}
};

var server = http.createServer(requestListener);
server.listen(8080);

In jsonString which is inside conn.query, I am getting value of rows printed. The last console.log is not printing anything, it is also jsonString.

Sorry, I am a newbie in node.js not aware of how to use objects.

Upvotes: 0

Views: 59

Answers (1)

Gaurav Gupta
Gaurav Gupta

Reputation: 4691

Javascript is async in nature.

 conn.query('select * from article where id=?', id,function(err,rows){
      if(err){
          console.log(err);
      }

      jsonString = rows;
    });

Try printing the jsonString within the callback. So, your code should look like

 conn.query('select * from article where id=?', id,function(err,rows){
      if(err){
          console.log(err);
      }

      jsonString = rows;
      console.log(jsonString);
    });

How your code is getting executed

  1. Assignment to var id is getting done.
  2. A query to db gets hit. This is time consuming process (async task), your callback function gets called when this query will get resolved. Note this will take some time, that means after sometime this callback will be called, where you will get the rows.
  3. Just after calling the query() ( but before getting the result/callback), your next line of code, i.e conn.end() will get executed. Then you are trying to print the jsonString, Note, till now you haven't got the results back from DB (as it is async operation). That's why jsonString doesnot holds any value yet. Hence you didnt get result printed.

Solution:

print the jsonString after retrieving the result. that means, in the callback.

Upvotes: 1

Related Questions