Nodejs and MySQL json feed

Twitter Facebook Pinterest Google+ Stumbleupon LinkedIn


If you’ve got experience of using Javascript I can’t recommend trying your hand at node.js more. It’s really versatile and easy to pick up, with it’s modern architecture it performs really well on processing a lot of information through things like feeds and can integrate well with a website built with a LAMP setup.

For that reason it’s perfect for JSON feeds, especially for a mobile app or website which has a lot of traffic.

Here’s a basic example of how you can pull information from a MySQL database and print it to the browser.

var http = require('http');

var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'database user name',
password : 'database password',
database : 'database name'
});

http.createServer(function (request, response)
{
console.log('Creating the http server');
connection.query('SELECT * FROM table WHERE field like "%search for%" limit 0,10', function(err, rows, fields)
{
console.log(rows);
console.log('Connection errors = '+err);
console.log('number of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.end(JSON.stringify(rows));
response.end();
});
}).listen(8081);

Posted by Adi on December 4, 2016

Twitter Facebook Pinterest Google+ Stumbleupon LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *