A simple way to read and write Redis databases in Node.js applications
- 2020-06-22 23:46:58
- OfStack
Before starting this article, make sure you have Redis and Node.js installed, as well as the Redis extension for ES4en.js, node_redis
First, create a new folder and a new text file app.js.
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 Redis, the runSample function is called and set a value, which is then read out as follows:
OK
Hello World
We can also use the EXPIRE command to set the expiration time of the object. The code is 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 an expiration
client.set('string key', 'Hello World', redis.print);
// Expire in 3 seconds
client.expire('string key', 3);
// This timer is only to demo the TTL
// Runs every second until the timeout
// occurs on the value
var myTimer = 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 used to demonstrate the EXPIRE command, you must use the timer carefully in the ES32en.js project.
The output of 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 has remained before it fails:
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 timer is only to demo the TTL
// Runs every second until the timeout
// occurs on the value
var myTimer = 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);
}
Operation results:
Reply: OK
I live: Hello World
I live for this long yet: 2
I live: Hello World
I live for this long yet: 1
I live: Hello World
I live for this long yet: 0
I expired