I am learning the book Redis Essentials by Maxwell Dayvson Da Silva and Hugo Lopes Tavares. It tells redis in node.js. The node.js in this book is very old, i.e. v0.12.4. And my node.js on my Ubuntu 20.04 is v10.19.0. I am working in python now. But I am familiar with JS in browsers, and with the hope that I can go through it, I decided to try the node.js. Could you tell me why the below code has not any output when I can ping-pong in redis-cli. Like below:
$ redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> SET key001 value001
OK
127.0.0.1:6379> GET key001
"value001"
127.0.0.1:6379> QUIT
$ node hello.js
$
(I have fixed the problem between line 2 and line 3, i.e. explicit connection.)
(I feel the root cause may be my node.js version is too higher than that in the book. I guess the process exits before the printing is executed. But I am not familiar with current node.js. Please help me!)
//hello.js
var redis = require("redis"); // 1
var client = redis.createClient(); // 2
client.connect(); // Important: explict conn is needed now!
client.set("my_key", "Hello World using Node.js and Redis"); // 3
client.get("my_key", redis.print); // 4
client.quit(); // 5
It is because the implementation of the redis client in nodejs is using Asyc/Await approach.
So, you may need to do something like the below instead.
(async () => {
const client = createClient();
client.on('error', (err) => console.log('Redis Client Error', err));
await client.connect();
await client.set('key', 'value');
const value = await client.get('key');
await client.quit();
})();