Quantcast
Channel: Louie Miranda » Programming
Viewing all articles
Browse latest Browse all 11

My first Node.js with MySQL pooling

$
0
0

I finally tried Node.js and it was fun! I tried to download the latest version at www.nodejs.org and compiled it from source.

Here’s a sample I made that binds on port 8888 and do connect on a mysql that pools.

Code here:

/**
* Javascript for Node.JS to responsd on data statistics requests
*
* @author Louie Miranda (lmiranda@gmail.com)
* @created July 3, 2013
*/
var http = require(“http”);
var url = require(“url”);
var mysql = require(‘mysql’);
var pool = mysql.createPool({
host : ‘localhost’,
user : ‘root’,
password : ‘****’,
database : ‘alerts’
});

start(route);

function start(route) {
function onRequest(request, response) {

pool.getConnection(function(err, connection) {
// Use the connection
connection.query(‘SELECT * from jobs’, function(err, rows) {
if (err) throw err;
console.log(rows);

//console.log(‘data:’ + data);
var pathname = url.parse(request.url).pathname;
console.log(“Request for ” + pathname + ” received.”);

route(pathname);

response.writeHead(200, {
//”Content-Type” : “text/plain”
“Content-Type” : “application/json”
});
//response.write(“Hello World”);
//response.write(rows[0].name);

response.write(JSON.stringify(rows, null, 0));

// And done with the connection.
response.end();
connection.end();

// Don’t use the connection here, it has been returned to the pool.
});
});

}
http.createServer(onRequest).listen(8888);
}

/**
* Test method
*/
function route(pathname) {
console.log(“About to route a request for ” + pathname);
}


Viewing all articles
Browse latest Browse all 11

Latest Images

Trending Articles





Latest Images