Powered By Blogger

Montag, 4. März 2013

Read/Write data using Redis with Node JS

Today is Redis day. ;-) Now I wrote a small JavaScript app for Node JS that can query and change a key:

var http = require('http');
var redis = require('redis'),
        client = redis.createClient();
var url = require('url');

console.log('talktoredis started!');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var testvalue = '';
  query = url.parse(req.url,true).query;
  client.get("testkey", function (err, reply) {
    testvalue = reply.toString();
    console.log('testvalue = ' + testvalue);
    res.write('Node.JS talks to Redis');
    res.write('Key "testkey" has value "' + testvalue + '".
');
    res.write('newvalue = "' + query.newvalue + '"
');
    res.write('Turn on ');
    res.write('Turn off');
    res.write('');
    res.end();
  });
  if (query.newvalue == 'on' || query.newvalue == 'off') {
    client.set("testkey", query.newvalue);
  }
}).listen(8000);


Together with my bash script written earlier this evening I can now use a web browser to change the behavior of a shell script.

A demonstration video was uploaded at YouTube.

EDIT: The source code isn't shown here correctly because it contains HTML tags. I uploaded the script here: https://www2.mkcs.at/temp/node_redis/talktoredis.js 

Keine Kommentare:

Kommentar veröffentlichen