Skip to content

Instantly share code, notes, and snippets.

@jameswalton
Created April 30, 2013 13:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameswalton/5488602 to your computer and use it in GitHub Desktop.
Save jameswalton/5488602 to your computer and use it in GitHub Desktop.
Node application to serve temperature readings
var http = require('http');
var fs = require('fs');
var url = require('url');
var fileLocation = '/sys/bus/w1/devices/28-000003b74282/w1_slave';
http.createServer(function (req, res) {
var request_url = url.parse(req.url).pathname;
if (request_url == '/temperature.json') {
fs.readFile(fileLocation, 'utf8', function(err, data) {
if (err) throw err;
matches = data.match(/t=([0-9]+)/);
temperatureC = parseInt(matches[1]) / 1000;
temperatureF = ((temperatureC * 1.8) + 32).toFixed(3);
output = '{ "temperature": { "celcius": '+ temperatureC +', "fahrenheit": '+ temperatureF +' } }';
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(output);
});
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('No route');
}
}).listen(8124, "0.0.0.0");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment