Skip to content

Instantly share code, notes, and snippets.

@oleics
Last active August 29, 2015 14:10
Show Gist options
  • Save oleics/36fd5049cf2f848e34a5 to your computer and use it in GitHub Desktop.
Save oleics/36fd5049cf2f848e34a5 to your computer and use it in GitHub Desktop.
Example: Asynchronously fetch and display database-rows (For NodeJs Beginners)
/*
An example for NodeJs beginners.
If you wonder how nodejs-code looks like when it
asynchronously fetches and displays rows from a
database, then this is for you.
*/
var fs = require('fs'),
http = require('http'),
mysql = require('mysql');
// HTTP Server
var server = http.createServer(handle_drawGraph_request);
server.listen(8080);
function handle_drawGraph_request(req, res) {
console.log("INCOMING REQUEST: " + req.method + " " + req.url);
getData(function(err, rows) {
if(err) {
console.error(err.stack||err);
sendError(req, res, err);
return;
}
var rowsAsJsonString = JSON.stringify(rows);
res.writeHead(200, {'Content-Type': 'text/html'});
res.write([
'<html><head></head><body>',
'<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>',
'<script src="http://code.highcharts.com/highcharts.js"></script>',
'<script src="http://code.highcharts.com/highcharts.js"></script>',
'<script>',
' var options = {',
' chart: {',
' renderTo: "container"',
' },',
' series: ['+rowsAsJsonString+']',
' };',
' chart1 = new Highcharts.Chart(options);',
'</script>',
'</body></html>',
].join('\n'));
res.end();
});
}
function sendError(req, res, err) {
res.writeHead(500);
res.write('Internal server error');
res.end();
}
// Database
dbclient = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "highcharts"
});
dbclient.connect();
function getData (callback) {
dbclient.query("SELECT * FROM eod_prod_last WHERE updatetime >= '2014-11-11 00:00:00'", function (err, rows) {
if (err) {
callback(err);
return;
}
callback(null, rows);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment