Archive | Node.JS RSS for this section

A Server.js response from two MySQL tables.

One thing that is a bit challenging is how to tespond from Server.Js when you have to get data out of two MySQL tables. Well it took a little digging but I finally found a solution.

This little bit of code write here. Uses the Q module from node. You can install it using npm install --save q .

Add this little code to your Server.Js.

app.get('/weather', function(req,res) {
 var res = res;
 var weather = {};

var deferredTandH = Q.defer();
var deferredPressure = Q.defer();

mysql.readLatestValues('BMP180', 1, deferredPressure.makeNodeResolver());
 
mysql.readLatestValues('TemperatureHumidity', 1, deferredTandH.makeNodeResolver());

Q.all([deferredTandH.promise, deferredPressure.promise]).then(function(results){
 weather.temperature = results[0][0].temperature;
 weather.humidity = results[0][0].humidity;
 weather.pressure = results[1][0].Pressure; 
 res.json(weather);
 });
});

In the code above there is a table named “BMP180” and “TemperatureHumidty”. These are the same ones shown in the previous post on setting up Server.Js.

That should do it. Now when both reads return you will process the promise in the then() method and you can return a single response.

Advertisements

Setting up Server.JS

To start with adding the following modules to you package.json using npm install –save body-parser express http moment winston This will save it in you package.json file. var express = require(‘express’); var app = express(); var bodyParser = require(‘body-parser’); var fs = require(‘fs’); var router = express.Router(); app.get(‘/’, function(req,res){ res.send(‘hello world’); }); app.listen(4000, function(){ console.log(‘started […]