title: node.js + MySQL & JSON-result - Callback-issue & no response to client
body: <p>I'd like to use node.js to query a mySQL-database and return the results as JSON to be used in a mobile application. Unfortunately, my request just sorta times out and the server does nothing for a good 2 minutes until the log-files show my <code>console.log()</code>-statements.</p>
  
  <p>Also, the callback doesn't return anything as result. It's just empty.</p>
  
  <pre><code>// Check dependencies
  var http = require('http');
  // Create the http server.
  // reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
  http.createServer(function(request, response) {
      // Attach listener on end event.
      request.on('close', function() {
          console.log('request');
  
          // run asynchronous 
          getSQL(function(err, result) {
              console.log('json:', result);
              response.writeHead(200, {
                  'Content-Type' : 'x-application/json'
              });
              // Send data as JSON string.
              response.end(result);
          });
      });
  }).listen(3000);
  
  // Access MySQL via node-mysql
  // https://github.com/felixge/node-mysql
  function getSQL(callback) {
      var mysql = require('mysql');
      var connection = mysql.createConnection({
          host : 'localhost',
          user : 'user',
          password : 'pw',
          database : 'db',
          socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian &lt;-&gt; client, seems not to be set correcly by default?
      });
  
      connection.connect();
      var json = '';
      var query = 'SELECT * FROM test';
      connection.query(query, function(err, results, fields) {
          if (err)
              return callback(err, null);
  
          console.log('The result is: ', results[0]);
  
          // wrap result-set as json
          json = JSON.stringify(results);
      });
      connection.end();
  
      callback(null, json);
  };
  </code></pre>
  
  <p>Output after like 2 minutes:</p>
  
  <pre><code>$ node app.js
  request
  json:
  The result is:  { test: 'avc' }
  json2: [{"test":"avc"}]
  </code></pre>
  
  <p>Based on my very basic understanding of the whole node.js-concept, my code should query the db (it does) and return a json once it's finished via the callback-function (apparently doesn't) which than is sent back as a response to the client (can't really check that since the json's empty).</p>
  
  <p>I guess I made one (or a couple) major mistakes. Help and/or helpful links would be much appreciated. Thanks!</p>
  
  <p><strong>Solution, thanks to hexacyanide</strong></p>
  
  <pre><code>// Check dependencies
  var http = require('http');
  // Create the http server.
  // reference: http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/
  
  /***************
  * Correction 1: Using the request.on('close', function()( ... )-listener isn't required anymore
  ***************/
  http.createServer(function(req, res) {
      console.log('Receving request...');
      var callback = function(err, result) {
          res.writeHead(200, {
              'Content-Type' : 'x-application/json'
          });
          console.log('json:', result);
          res.end(result);
      };
  
      getSQL(callback);
  
  }).listen(3000);
  
  // Access MySQL via node-mysql
  // https://github.com/felixge/node-mysql
  function getSQL(callback) {
      var mysql = require('mysql');
      var connection = mysql.createConnection({
          host : 'localhost',
          user : 'user',
          password : 'pw',
          database : 'db',
          socketPath : '/var/run/mysqld/mysqld.sock', // socket for communication from debian &lt;-&gt; client, seems not to be set correcly by default?
      });
  
      connection.connect();
      var json = '';
      var query = 'SELECT * FROM test';
      connection.query(query, function(err, results, fields) {
          if (err)
              return callback(err, null);
  
          console.log('The query-result is: ', results[0]);
  
          // wrap result-set as json
          json = JSON.stringify(results);
  
          /***************
          * Correction 2: Nest the callback correctly!
          ***************/
          connection.end();
          console.log('JSON-result:', json);
          callback(null, json);
      });
  };
  </code></pre>