I'm learning to use mysql
module in node.js, so I use it with Express
& Mustache
to render a MySQL table and came up with this:
var express = require('express');
var app = express();
var mu2 = require('mu2');
mu2.root = __dirname + '/views';
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
port: 3306,
database: 'breakthrough'
});
con.connect(function (err) {
if (err) {
console.log('Error connecting to database:\n' + err);
return;
}
});
app.get('*', function (req, res) {
var tableHTML;
function renderTable(rows) {
tableHTML = "<table>";
for (var row in rows) {
tableHTML += "<tr>";
for (var cell in row) {
tableHTML += ("<td>" + cell + "</td>");
}
tableHTML += "</tr>";
}
tableHTML += '</table>';
}
con.query('SELECT * FROM drivers', function (err, rows){
if (err) { throw(err); }
renderTable(rows);
htmlStream = mu2.compileAndRender('frontPage.html', {table: tableHTML});
htmlStream.pipe(res);
});
});
app.listen(8080, function () {
console.log("Listening on port 8080.");
});
But the resulting table only show zeroes, one for each row:
<table>
<tr><td>0</td></tr>
<!-- tr repeated for each row in rows -->
</table>
Some readings suggest that iterating over objects in node.js is currently quite problematic. Is there any way I can lazy-iterate over node.js objects?