Skip to content

Instantly share code, notes, and snippets.

@danielkhan
Last active June 5, 2018 09:32
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielkhan/d41c09c19e225d193d90 to your computer and use it in GitHub Desktop.
Save danielkhan/d41c09c19e225d193d90 to your computer and use it in GitHub Desktop.
// Require nodes http module
var http = require('http');
// Require a third party mysql module (use "npm install mysql" to install it)
var mysql = require('mysql');
// Create a connection pool
var pool = mysql.createPool({
host: 'localhost',
user: 'username',
password: 'password',
database: 'test'
});
// Create an instance of http server that listens on localhosts port 3000
var server = http.createServer().listen(3000, '127.0.0.1', function () {
var port = server.address().port;
console.log('http server is listening on port %s', port);
});
// Register a callback to the 'request' event
server.on('request', function (request, response) {
// Request a connection from the pool and define a callback
pool.getConnection(function (error, connection) {
if (error) {
response.writeHead(500, {'Content-Type': 'text/html'});
response.write("Error connecting to database: " + JSON.stringify(error));
response.end();
return;
}
// We got a connection object and call the query on it and define a callback
connection.query('SELECT * FROM Person', function (error, rows) {
if (error) {
response.writeHead(500, {'Content-Type': 'text/html'});
response.write("Error when selecting from database: " + JSON.stringify(error));
response.end();
return;
}
// Free the connection
connection.release();
response.writeHead(200, {'Content-Type': 'text/html'});
// Send result as string to the browser
response.write(JSON.stringify(rows));
response.end();
});
});
});
// Define some error handler
var onError = function (error) {
console.log('onError: ');
console.log(error);
process.exit(1);
};
var onUncaughtException = function (ex) {
console.log('onUncaughtException: ');
console.log(ex);
console.log(ex.stack);
process.exit(1);
};
// HTTP Server level error like EADDRINUSE
server.on('error', onError);
// Uncaught exceptions
process.on('uncaughtException', onUncaughtException);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment