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 

Get values from redis server from bash

Getting values from a redis server is also possible in (bash) shell scripts. On Github, I found a project providing two files (redis-bash-lib and redis-bash-cli) which enable such functionality. I wrote a small script that monitors a key for changes and writes a message to the screen, if the monitored key changes:

#!/bin/bash
SOMEVAR=''
OLDVAR=''
while /bin/true; do
    SOMEVAR=`redis-bash-cli -h localhost GET testkey`;
    if [ "$SOMEVAR" != "$OLDVAR" ]
    then
        echo "Value has changed from $OLDVAR to $SOMEVAR";
    fi
    OLDVAR=$SOMEVAR;
    sleep 1;
done;


Just open a terminal, start "redis-cli" und enter "set testkey perhaps", "set testkey again" or any other values and see how the script reacts to that change.

You could use redis server to exchange commands between some other software and your script. The script could evaluate the value and execute commands.