Tutorials > How to create a Web App with Node.js and Redis on Ubuntu 20.04

How to create a Web App with Node.js and Redis on Ubuntu 20.04

Published on: 10 September 2020

Node.js Redis Ubuntu

In the following tutorial you will see how to create the basics of a Web App using Node.js together with Redis. Redis datastore is widely used as a database for caching, as well as for managing applications that require exchange of messages in real time.

Your sample application will answer REST calls, allowing the client to save and read a book archive.

Express will be used as a web framework for handling HTTP requests, while Redis will allow you to permanently save information on the disk.

To get started connect to your Ubuntu 20.04 server via an SSH connection. If you haven’t done so yet, following our guide is recommended to to  connect securely with the SSH protocol. In case of a local server, go to the next step and open the terminal of your server.

Installing Redis

First, update the package repository using the following command:

sudo apt update

Then, proceed by installing the "redis-server" package:

sudo apt install redis-server -y

To test the installation and learn the first Redis instructions, connect to the database through the command:

redis-cli

The first command to learn is SET: this command allows you to permanently set the value of a key in the database.

Then, use the command to assign the value "hello world" to the key "testKey":

SET testKey “hello world”

The Redis keys allow you to store any type of data including strings, numbers or binary sequences such as images and files. It is important to know, however, that the maximum size of a Redis key cannot exceed 512 Mb.

To get the current value of a Redis key, use the GET command followed by the key name:

GET testKey
“hello world”

Another useful instruction that can come in is the INCR: it allows you to increase the current key of a unit as shown below.

SET testKey 100
INCR testKey

Rereading the value of testKey, the key will return 101:

GET testKey
101

Then, proceed by deleting the key used for these tests using the DEL statement:

DEL testKey

Now, end the session with QUIT command.

Installing Node.js and npm

First, install Node.js and the npm package manager through the following command:

sudo apt install nodejs npm -y

To create an application compatible with the standards set by Node.js, initialize a basic configuration of npm.

Then, create a folder for the project (in this example called "books") and move inside it.

mkdir books
cd books

Run the following console command inside the newly created folder:

npm init

A wizard will be started to create a package.json file, which will contain all the basic information about the project and its dependencies.

Use the suggested values ​​to go on, as shown below:

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (books)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to package.json:

{
 "name": "books",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
 "test": "echo \"Error: no test specified\" && exit 1"
 },
 "author": "",
 "license": "ISC"
}

Is this OK? (yes) yes

Answer yes to complete the procedure.

Then, continue by installing the two main modules:

npm install --save express ioredis

By adding the --save parameter, npm is told to update package.json, adding these two dependencies to the project.

Creation of Express application

At this point,proceed with the setting of the entry point for your Express application, by creating the index.js file in the same directory as package.json.

Use your favorite text editor to paste the following content into the newly created file:

/**
* First, include the two previously installed modules 
* 
*/
var express = require('express');
var Redis = require( 'ioredis' );

const redis = new Redis();

/**
* Initialize a new Express application
*/
var app = express();

/**
* Use the main server root to list all the books 
* 
*/
app.get('/', function (req, res) {

 redis.lrange( "books" , 0, -1 ).then( rows => {

 /**
 * Send all the lines found in the “books” chart
 */

 res.send( rows );
 });

});

/**
* Then, to save it, use the path /save/ followed by the title and the author of the book. 
* /save/ seguito dal titolo e dall'autore
*/
app.get('/save/:title/:author', function (req, res) {

 /**
 * Prepare the data in object format
 */
 var data = { title: req.params.title, author: req.params.author };

 /**
 * And insert the object in text format in a “books” list
 */

 redis.lpush( "books" , JSON.stringify( data ) ).then( () => {
 res.send(true);
 });

});

/**
* Then, start the listening server on the port 8001
*/

app.listen (8001, function () {
 console.log('Books server ready');
});

At this point, start the server using the command:

node index.js

Through your favorite browser, visit the following URL. Make sure you change the IP address with that of your server and use port 8001:

http://SERVER_IP:8001/

If everything works correctly, your Web App will reply with:

[]

Then, use your browser to save the first 3 books by visiting the following urls:

http://SERVER_IP:8001/save/Il%20Decamerone/Giovanni%20Boccaccio

http://SERVER_IP:8001/save/Il%20fu%20Mattia%20Pascal/Luigi%20Pirandello

http://SERVER_IP:8001/save/Il%20barone%20rampante/Italo%20Calvino

NB Remember to always replace the address "SERVER_IP" with that of your server.

So, make sure the books have been saved by navigating to the previously used URL :

http://SERVER_IP:8001/

The server should respond with the following content:

[{"title":"Il Decamerone","author":"Giovanni Boccaccio"},{"title":"Il fu Mattia Pascal","author":"Luigi Pirandello"},{"title":"Il barone rampante","author":"Italo Calvino"}]

If so, you have correctly followed all the instructions and created your first working Web App with Node.js and Redis. The newly created application will respond to REST calls and allow users to save and read a book archive.