I'm trying Node.js
for the first time, everything works, but i'm not sure that my approach is right, can you tell me if it's ok?
In this test, i've tried to get sample data from mysql db and print it on http response.
I didn't even understand how to call the res.end();
if i have many async tasks working ^^
//IMPORTS
var http = require('http');
var mysql = require('mysql');
//---------------------------------------------------
//HTTP RESPONSE
http.createServer(function (req, res) {
fetchActors(res);
}).listen(8080);
//---------------------------------------------------
//MISCS
//Database connection string
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "*********",
database: "sakila"
});
//Connection to database
db.connect(function(err) {
if (err) throw err;
console.log("Connected to Database!");
});
//-----------------------------------------------------
//FUNCTIONS
//Exectues queries on declared db (it can be extended if you want to use more than one db)
function executeQuery(sql, cb) {
db.query(sql, function (err, result, fields) {
if (err) throw err;
cb(result);
});
}
//Prints actors table
function fetchActors(res){
executeQuery("SELECT * FROM actor", function(result){
res.write("<table>");
res.write("<tr>");
for(var column in result[0]){
res.write("<td><label>" + column + "</label></td>");
}
res.write("</tr>");
for(var row in result){
res.write("<tr>");
for(var column in result[row]){
res.write("<td><label>" + result[row][column] + "</label></td>");
}
res.write("</tr>");
}
res.write("</table>");
});
}