JavaScript in Plain English
By: Louis Petrik
Tags: Web Development, Programming, Backend Development, Nodejs, Redis

Performance & simplicity in two technologies. It’s a match!

I don’t want to do long talk here.

Let’s start with explaining & installing Redis on your machine, covering the basics of the Redis CLI & then use it in Node.js. For now we will only work with simple datatypes in Redis. Because that is what we need mostly.

Good news here: Whether you use Redis with Node or any other programming langauge — it will be pretty similar everywhere once I have introduced you to the most important commands in Redis.

What is Redis, and why is it so cool?

Redis is an in-memory database, that works with key values. So for each value, there is one key. Therefore Redis is not an SQL database, and is designed for primitive data structures, which we will work with in this article. Because of the speed of reading and writing data with Redis, and the simple key-value system, Redis can be used wonderfully for e.g. caches.

Permanent data such as user information or images, however, should not be stored with Redis because of its volatility. Are you already hungry for more? Let’s go!

Installing Redis on your machine

Linux:

https://redis.io/topics/quickstart

sudo service redis start or sudo service redis-server start

MacOS:

Install brew, in case you do not have it already installed: https://brew.sh/

brew install redis

brew services start redis

Windows: Use the Linux Subsystem for Windows. Then just install it like on linux.

Check, if Redis is working:

Once you already started the Redis service, you should be able to communicate with it, via the redis-cli. Try to do redis-cli ping

and Redis should anser with “PONG”. That means, Redis is working.

The Redis CLI

When your Redis is running, you can always use redis-cli to directly connect to it. In the CLI you can run all of Redis commands, so let’s have a look on a few.

Working with a simple String

Note: Whether we capitalize SET and other commands is irrelevant in the CLI.

The principle for simple data is simple. We say SET, then give the key, i.e. the variable name, and with a space after it, simply the value.

SET name Max

Now we can print out the value of our key, called “name”. We should receive “Max”

GET name

When we have played enough with our name we can of course delete it again. After that a (nil) should expect us when we try to access the already deleted value again.

DEL name

GET name // (nil) will be printed.

But maybe we want to save another name afterwards. To do this, let’s first create a single name again, and deliberately name the key “names”

SET names Max

Now we can extend this string, which in this case I will do with quotation marks, so that Redis will also include spaces & special characters.

APPEND names “ & Matt”

As before, we should now be able to output the completed string again. We should get “Max & Matt”.

But how could we elegantly realize a cache now?

Good question, I think. Apparently you were careful at first when I said Redis is great for this.

Well, the point of a cache is to store data temporarily. Now we know how to erase data, but for a whole cache that would be a bit cumbersome.

Therefore Redis offers the possibility to expire data automatically after a time defined by us.

We can do this two ways:

1) Either we specify directly when creating the key, after how many seconds it should expire.

2) Or we determine this afterwards. Again, the number we pass is the number of seconds until the key expires.

// 1) The name-key will expire after 60 seconds

SET name Max EX 60 // 2) First we define the name

SET name Max

// Then we define when to expire

EXPIRE name 60

So if it has been determined that a key should expire at some point, we can also read out the current remaining lifetime at any time. Just to make it clear again: Only the remaining time, which of course changes every second, is output.

SET name Max EX 60 // get the remaining time

TTL name // will be 60, 59, 58 etc...

But we’d still need one more thing for a working cache…

We can now delete keys manually and automatically. But what if we just want to check if our key is still there?

For this there is the exists function in Redis. It returns 1 if the key exists and 0 if it does not.

SET name Max

EXISTS name

// will return: (integer) 1 DEL name

EXISTS name

// will return: (integer) 0

Now you are familiar with the CLI and the most important commands in Redis. Now let’s put this into practice — with Node.js!

Getting started with Redis in Node.js

First we need to install Redis in our Node.js project:

npm install redis

Then we can import it in our code, and connect to our Redis instance on our machine. The parameter for the createClient will be the address of our instance on our machine (that’s why we use localhost) and the port 6379 is the default port for Redis.

const redis = require(‘redis’)

const client = redis.createClient(‘redis://localhost:6379’)

That’s it so far. Now we can use it in Node, with the same commands as before.

So you should remember this command:

SET name Max

This is the same, just for Node.js:

client.set(‘hi’, ‘there’)

As you can see, it’s almost the same. Only the syntax changes a bit, via the client object we always just access the corresponding command after the point. Of course, in JavaScript we have to pass strings in quotation marks, in the CLI itself this is not a must.

So, here are all of the commands we already learned. With a comparison to Node.js

GET name

client.get('name', (error, value) => {

console.log(value)

}) // or to print it out directly: (Will not just print out the value)

client.get('name', console.log)

As you can see, we always use another function for all commands where we get something. The first parameter gives us possible error messages, the second is the actual result.

And yes, for the direct output shown in the second example, we can write a console.log directly into the function. Important: The output should be “null Max”, but the “null” here only means that no error occurred. In the first example, the “value” is only used to output the value of the key directly.

Next example, deleting:

DEL name client.del(‘name’)

Appending:

APPEND name ‘ & Tom’ client.append(‘name’, ‘ & Tom’)

Determine directly when the key should expire:

SET name Max EX 60 client.set('name', 'Max', 'EX', 60)

And how we can do it afterwards:

EXPIRE name 60 client.expire('name', 60)

Remaining time until expiration:

TTL name client.ttl(‘name’, (error, value) => {

console.log(value)

})

Checking if the key exists: (JavaScript will see 0 as false, 1 as true of course)

EXISTS name client.exists('name', (error, value) => {

if (value) {

console.log('Key does exist')

} else {

console.log('Key does not exist')

}

})

I think now the principle should be clear. The syntax for Node.js is absolutely fixed for the types of commands, so you are now able to extend your knowledge of Redis on your own and implement newly learned commands not only in the CLI but also in Node.js. Wasn’t that hard after all :)

But here’s an extra for you — because we all like to work with Objects & JSON. Here is how to save a JS object in Redis. And then how to print it out

client.set(‘name’,

JSON.stringify({ firstname: ‘max’, lastname: ‘meyer’})

)

client.get(‘name’, (err, val) => {

console.log(JSON.parse(val))

})

Thanks for reading it. If you have additions, write them down in the comments. I plan to add to this article all the time, so feel free to check back often.

And one last thing before you can finally have fun alone with Redis: Leave me a clap, it doesn’t cost anything :)

About me, the author :)

Hi! Thank you very much again for reading, my name is Louis and I am a 18 years old student from Germany. I am in love with Web development, both backend and frontend. My favorite technologies are React, Vue, React Native and Node.js.

Make sure to follow me for more content related to those, and feel free to have a look on my IG’s @louis.jsx & @codingcultureshop

Have a nice day!