Before you begin this article, be sure to install the Redis extensions for Redis and Node.js and Node.js--node_redis
First create a new folder and new text file app.js the contents of the file are as follows:
var Redis = require ("Redis")
, client = Redis.createclient ();
Client.on ("Error", function (err) {
Console.log ("error" + err);
});
Client.on ("Connect", runsample);
function Runsample () {
//Set a value
client.set ("String Key", "Hello World", function (err, reply) {
console. Log (reply.tostring ());
});
Get a value
client.get ("string Key", function (err, reply) {
console.log (reply.tostring ());}
);
When connected to the Redis, the Runsample function is called and a value is set, followed by a readout of the value, running as follows:
We can also use the EXPIRE command to set the expiration time of an object, as follows:
var Redis = require (' Redis ')
, client = Redis.createclient ();
Client.on (' Error ', function (err) {
console.log (' error ' + err);
});
Client.on (' Connect ', runsample);
function Runsample () {
//Set a value with the Expiration
client.set (' string key ', ' Hello World ', redis.print);
//Expire in 3 seconds
client.expire (' string key ', 3);
This is the ' only ' to Demo ' TTL
//runs every second until the timeout
//occurs on the value
var myt Imer = setinterval (function () {
client.get (' string key ', function (err, reply) {
if (reply) {
Console.log (' I Live: ' + reply.tostring ());
} else {
cleartimeout (mytimer);
Console.log (' I expired ');
Client.quit ();
}
});
}, 1000);
Note: The timer used above is only to demonstrate the EXPIRE command, you must use the timer carefully in the Node.js project.
The output from running the above program is:
Reply:ok i Live:hello World i live:hello World I live:hello World I
expired
Next we check how long a value is persisted before it expires:
var Redis = require (' Redis ')
, client = Redis.createclient ();
Client.on (' Error ', function (err) {
console.log (' error ' + err);
});
Client.on (' Connect ', runsample);
function Runsample () {
//Set a value
client.set (' string key ', ' Hello World ', redis.print);
Expire in 3 seconds
client.expire (' string key ', 3);
This is the ' only ' to Demo ' TTL
//runs every second until the timeout
//occurs on the value
var myt Imer = setinterval (function () {
client.get (' string key ', function (err, reply) {
if (reply) {
Console.log (' I Live: ' + reply.tostring ());
Client.ttl (' string key ', Writettl);
} else {
cleartimeout (mytimer);
Console.log (' I expired ');
Client.quit ();
}
});
}, 1000);
function Writettl (err, data) {
Console.log (' I live for this long yet: ' + data);
}
Run Result:
Reply:ok i Live:hello world I live for this long yet:2 i Live:hello world I live for t His long yet:1 i Live:hello world I live for this long yet:0 I expired