cannot response.write on connection node.js


I wrote this code in node.js :

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'hostname',
      user     : 'user',
      password : 'pass',
      database : 'dbname',


    connection.query('SELECT code FROM user_type', function(err, rows, fields) {
      if (err) throw err;
            //This for is to run on all the results
            for(var i=0;i<2;i++){


console.log('Server running');

my questions are: 1. why did the res.write in the for loop print nothing in my html page? 2. what to write instead of 2 in the for?

Problem courtesy of: royb


  1. The issue is the timing of execution.

    Since connection.query() is asynchronous, it delays the execution of the callback function to when the query finishes, but allows the surrounding block of code to continue in the meantime. This results in res.end('End') being executed before res.write('name:',rows[i].code).

    To also delay res.end(), move it inside the callback:

    connection.query(..., function(err, rows, fields) {
        if (err) throw err;
        for (...) {
  2. rows should be an Array when there isn't an err, so you can use its length property:

    for (var i = 0; i < rows.length; i++) {

    It's also a common practice to store the value of length in a local variable:

    for (var i = 0, len = rows.length; i < len; i++) {
Solution courtesy of: Jonathan Lonowski


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.