Many of the applications use Redis for improving the application performance. Redis is not only used for the caching purpose. Redis supports many of the data types. Redis also support publish and subscription functionality. We can cluster the Redis database. Redis serve as in-memory, key-value data stores, although Redis is more accurately described as a data structure store.
Here in this article I'm going to use Redis with Node.js. I'll register the user in Redis database by using hmset command. I'm assuming that you have installed Redis, Node.js and NPM on you machine.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
{
"name": "Redis-Node-CRUD",
"version": "0.0.1",
"main": "app.js",
"author": "Coding 4 Developers",
"description": "An example of Redis & Node.js",
"dependencies": {
"ejs": "^2.5.7",
"body-parser": "*",
"express": "*",
"redis": "*"
}
}
|
Now I'll install all the dependencies by node package manager (NPM). Run the below commend:
1
|
npm install
|
Now I'll be creating the entry point js file like app.js.
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
let express = require('express');
let path = require('path');
let bodyParser = require('body-parser');
let port = process.env.port || 3000;
let app = express();
app.use(express.static(__dirname + "/public" ));
app.set('view engine', 'ejs');
// DB connection
let redis = require('redis');
let client = redis.createClient();
client.on('connect',function(){
console.log('Redis connected successfully!!!!!');
});
// DB connection end
// body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
// body parser end
app.get('/',function(req,res){
res.render('users');
});
app.post('/users/search',function(req,res){
let userId = req.body.userId;
client.hgetall(userId,function(err, data){
if(!data){
res.render('users',{message: "No user exist"});
}else{
data.userId = userId;
res.render('users',{users: data});
}
})
});
app.get('/users/add',function(req,res){
res.render('add-user');
});
// hmset command accepts multiple key value at a time and overwrites any specified fields already existing in the hash. If key does not exist, a new key holding a hash is created.
app.post('/users/add',function(req,res){
let userId = req.body.userId;
let name = req.body.name;
let email = req.body.email;
let password = req.body.password;
client.hmset(userId, ["name", name, "email", email, "password", password],function(err,response){
if(err){
console.log(err);
}else{
console.log(response);
res.render('add-user',{message: "User added successfully!!!!"});
}
});
});
app.get('/users/delete/:userId',function(req,res){
client.del(req.params.userId,function(err,result){
if(err){
console.log(err);
}else{
res.redirect('/');
}
});
});
app.listen(port,function(){
console.log("Server running at port "+ port);
});
|
Here in app.js I have includes all the modules which I required. I have defined my application port as 3000 and I'm using ejs template engine for views. Later I have created a Redis client which is helping to query with Redis.
I also have used body parser here so that when I'll be sending any form data I can get the parse the request body.
For views create a directory views and put ejs code into that directory. I have used bootstrap for giving better look and feel. I'm creating partials as well like we have navigation which I wanted to keep in separate file. I also have some bootstrap CSS and JS which I wanted to use on every page so I'm keeping header and navigation in partials.
views/partials/header.ejs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="A demo of Redis and Node.js">
<meta name="author" content="Coding 4 Developers">
<title>Redis & Node Example</title>
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="https://getbootstrap.com/docs/4.0/examples/navbar-top-fixed/navbar-top-fixed.css" rel="stylesheet">
</head>
|
views/partials/nav.ejs
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="/">Search User</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/users/add">Add User</a>
</li>
</ul>
</div>
</nav>
|
views/users.ejs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<% include partials/header %>
<% include partials/nav %>
<body>
<main role="main" class="container">
<% if (typeof message != 'undefined' && message) { %>
<h2><%= message %></h2>
<% } %>
<form class="form-inline mt-2 mt-md-0" method="post" action="/users/search">
<input class="form-control mr-sm-2" type="text" name="userId" value="<% if (typeof users != 'undefined') { %><%= users.userId %><% } %>" placeholder="User Id" aria-label="User Id">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
<%
if (typeof users != 'undefined') {
%>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><%= users.name %></td>
<td><%= users.email %></td>
<td><a href="/users/delete/<%= users.userId %>" title="Delete User"><button class="btn btn-danger">Delete</button></a></td>
</tr>
</tbody>
</table>
<%
}
%>
</main>
</body>
</html>
|
I have declared in app.js that on home route users.ejs is the home page view. Here I have a search form through which I can search the users in Redis by user id. If the user found I also list the user in table else will print the message that no user exist. You also can delete the user from Redis database by clicking on Delete button.
views/add-user.ejs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
<% include partials/header %>
<% include partials/nav %>
<body>
<div class="container">
<% if (typeof message != 'undefined' && message) { %>
<h2><%= message %></h2>
<% } %>
<form method="post" action="/users/add">
<div class="form-group">
<label>User Id</label>
<input type="text" name="userId" class="form-control" placeholder="User Id">
</div>
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<label>Email address</label>
<input type="email" name="email" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</body>
</html>
|
Here is the form to add the user. I'm keeping the user id as key in Redis hmset. I'm searching the user by user id.
Run you project with below command:
1
|
node app.js
|