Execute Redis Commands with Node.js without Driver

We had written about redis commands through node.js previously.

Below is a code snippet, where we have connected and executed redis commands from node.js without using any driver.

Steps taken –

1> First we have started Redis in our machine.

2> We have written a bare minimum socket program to connect the redis host and port( 127.0.0.1 and 6379). below is connection related code –

client.connect method…

3> In connect method, we have written the commands of Redis. (Some examples are SET, GET, ECHO and PING )

The most important part here is the EXEC command of redis, which will execute all the commands in Queue.

4> We have taken callback from ‘data‘ and ‘close‘ event in node.js

In data event callback, we have got the response from Redis Server.

5> In ‘close’ event we have got callback for socket closing.

Here the work is only for exploration purpose. We will create more structural classes for redis data handling in future, for which we will update important parts in next posts.

Below is the code.

 
var net = require('net');

var HOST = '127.0.0.1';
var PORT = 6379;

var client = new net.Socket();
client.connect(PORT, HOST, function() {

    console.log('CONNECTED TO: ' + HOST + ':' + PORT);
    // Send message to socket after client connection
    client.write('SET samplekey "Hello"\r\n');
    client.write('GET samplekey\r\n');
    client.write('ECHO "HELLO WORLD"\r\n');
    client.write('PING\r\n');
    client.write('EXEC');

});

// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {

    console.log('DATA: ' + data);
    // Close the client socket completely
    client.destroy();

});

// Add a 'close' event handler for the client socket
client.on('close', function(err) {
    if(err)
	console.log(err);
    console.log('Connection closed');
});

If you find this article helpful, you can connect us in Google+ and Twitter

Leave a Reply

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