Generate a QR Code in Node

Introduction

 
In this blog, you will learn how to generate a QR code in Node. 
 

Project Structure

  
      | --------- models
      |                 |-------- user.js
      |
      |---------- views
      |                 |-------- home.ejs
      |
      |----------- app.js
 

Setup the Folder

 
First, we have to create a folder for our project.
  • Open the command prompt /terminal and type mkdir command followed by the folder name.

    # mkdir qrcodee
  • Now change to that folder using cd followed by the folder name.

    # cd qrcodee

Setup Node in Folder

 
To setup node in the folder, we have to type the following command from the command prompt/terminal.
 
# npm init -y

This will create a package.json file in the folder which means that Node has been set up in our folder. The file will look like this.
  1. {    
  2.   "name""qrcodee",  
  3.   "version""1.0.0",    
  4.   "description""",    
  5.   "main""index.js",    
  6.   "scripts": {    
  7.     "test""echo \"Error: no test specified\" && exit 1"    
  8.   },    
  9.   "keywords": [],    
  10.   "author""",    
  11.   "license""ISC"    
  12. }   

Install Packages

 
To build our application, we need to install packages. For installing the packages, we have to use the below command followed by the package name.
 
# npm install body-parser ejs express mongoose QRcode
 
After the packages are installed, the package.json will look like this.
  1. {    
  2.   "name""qrcodee",    
  3.   "version""1.0.0",    
  4.   "description""",    
  5.   "main""index.js",    
  6.   "scripts": {    
  7.     "test""echo \"Error: no test specified\" && exit 1"  
  8.   },    
  9.   "keywords": [],    
  10.   "author""",    
  11.   "license""ISC",    
  12.   "dependencies": {    
  13.     "body-parser""^1.19.0",    
  14.     "ejs""^3.0.1",    
  15.     "express""^4.17.1",    
  16.     "mongoose""^5.8.11",    
  17.     "qrcode""^1.4.4"    
  18.   }    
  19. }  

Add New Folders

 
Now add 2 new folders in our project folder:
  • models
  • views
Models Folder
 
Add a file to it and name it user.js.
 
user.js
  1. var mongoose    =   require('mongoose');    
  2.     
  3. var userSchema  =   new mongoose.Schema({    
  4.     name:{    
  5.         type:String    
  6.     },    
  7.     phno:{    
  8.         type:Number    
  9.     }    
  10. });    
  11.     
  12. module.exports = mongoose.model('user',userSchema);   
  • mongoose.schema() - this is used to create the collection(table) schema.
  • mongoose.model() - here we will provide the name to our schema by which we can access it and can do data manipulation in it.
Views Folder
 
Add a new file to it and name it home.ejs
 
home.ejs
  1. <html lang="en">    
  2. <head>    
  3.     <meta charset="UTF-8">    
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">    
  5.     <meta http-equiv="X-UA-Compatible" content="ie=edge">    
  6.     <title>Qrcode</title>    
  7.     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">    
  8. </head>    
  9. <body>    
  10.     <div class="nav justify-content-center">    
  11.     <div class="card border-primary mb-3" style="max-width: 18rem;margin-top: 20px;">    
  12.         <div class="card-header">User Details</div>    
  13.         <div class="card-body text-primary">    
  14.             <form action="/" method="post">    
  15.                 <input type="text" name="name" placeholder="enter the name" class="form-control"><br>    
  16.                 <input type="text" name="phno" placeholder="enter the phone number" class="form-control"><br>    
  17.                <div class="text-center"> <input type="submit" value="get qrcode" class="btn"> </div>     
  18.              </form>    
  19.         </div>    
  20.       </div>    
  21.     </div>    
  22.     <%if(data){%>     
  23.         <div class="text-center">    
  24.          <h5>Scan QRCode</h5>    
  25.         <img src="<%=data%>" alt="" style="width:100px; height:100px;">    
  26.          </div>    
  27.     <%}%>      
  28. </body>    
  29. </html>   

Set The Start Point

 
In the project folder add a new file and name it app.js.This is the starting point of our application
 
app.js
  1. var express     =   require('express');    
  2. var mongoose    =   require('mongoose');    
  3. var userModel   =   require('./models/user');    
  4. var bodyParser  =   require('body-parser');    
  5. var QRCode      =   require('qrcode');    
  6.     
  7. //connect to db    
  8. mongoose.connect('mongodb://localhost:27017/qrdemo',{useNewUrlParser:true})    
  9. .then(()=>console.log('connected to db'))    
  10. .catch((err)=>console.log(err))    
  11.     
  12. //init app    
  13. var app = express();    
  14.     
  15. //set the template engine    
  16. app.set('view engine','ejs');    
  17.     
  18. //fetch data from the reuqest    
  19. app.use(bodyParser.urlencoded({extended:false}));    
  20.     
  21. //default page load    
  22. app.get('/',(req,res)=>{    
  23.        userModel.find((err,data)=>{    
  24.           if(err){    
  25.               console.log(err);    
  26.           }else{    
  27.               if(data!=''){    
  28.                   var temp =[];    
  29.                   for(var i=0;i< data.length;i++){    
  30.                       var name = {    
  31.                           data:data[i].name    
  32.                       }    
  33.                       temp.push(name);    
  34.                       var phno = {    
  35.                           data:data[i].phno    
  36.                       }    
  37.                       temp.push(phno);    
  38.                   }   
  39.                   // Returns a Data URI containing a representation of the QR Code image.  
  40.                   QRCode.toDataURL(temp,{errorCorrectionLevel:'H'},function (err, url) {    
  41.                     console.log(url)    
  42.                     res.render('home',{data:url})    
  43.                   });    
  44.               }else{    
  45.                   res.render('home',{data:''});    
  46.               }    
  47.           }    
  48.        });    
  49. });    
  50.     
  51. app.post('/',(req,res)=>{    
  52.         var userr = new userModel({    
  53.             name:req.body.name,    
  54.             phno:req.body.phno    
  55.         });    
  56.         userr.save((err,data)=>{    
  57.              if(err){    
  58.                  console.log(err);    
  59.              }else{    
  60.                  res.redirect('/');    
  61.              }    
  62.         });    
  63. });    
  64.     
  65. //assign port    
  66. var port  = process.env.PORT || 3000;    
  67. app.listen(port,()=>console.log('server run at '+port));   
Now open the package.json file and in the script, add "start":"node app.js"
 
The package.json file will look like this:
  1. {    
  2.   "name""qrcodee",    
  3.   "version""1.0.0",    
  4.   "description""",    
  5.   "main""index.js",    
  6.   "scripts": {    
  7.     "test""echo \"Error: no test specified\" && exit 1",    
  8.     "start""node app.js"    
  9.   },    
  10.   "keywords": [],    
  11.   "author""",    
  12.   "license""ISC",    
  13.   "dependencies": {    
  14.     "body-parser""^1.19.0",    
  15.     "ejs""^3.0.1",    
  16.     "express""^4.17.1",    
  17.     "mongoose""^5.8.11",    
  18.     "qrcode""^1.4.4"    
  19.   }    
  20. }    
References
  • https://www.npmjs.com/package/qrcode