royb
royb

Reputation: 713

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'});
    res.write('start\n');
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
      host     : 'hostname',
      user     : 'user',
      password : 'pass',
      database : 'dbname',
    });

    connection.connect();

    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++){
            res.write('name:',rows[i].code);
        }
    });

    connection.end();

  res.end('End');
}).listen(8080);
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?

Upvotes: 0

Views: 980

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

  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 (...) {
            res.write('name:',rows[i].code);
        }
        res.end('End');
    });
    
  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++) {
    

Upvotes: 3

Related Questions