How to Create and Read QR Code in Node.js

A QR code, which stands for Quick Response code, is a type of two-dimensional barcode that can be scanned by digital devices. It's essentially a square-shaped grid filled with black and white squares that represents information.

With the increase in digital devices, you can access any data by just scanning it. There are various use cases of QR Code like in sales & marketing, for eg. you can store all the details of a product in QR Code. In this tutorial, you will learn how to Create a QR code in Node.

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.

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

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.

{    
  "name": "qrcodee",    
  "version": "1.0.0",    
  "description": "",    
  "main": "index.js",    
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1"  
  },    
  "keywords": [],    
  "author": "",    
  "license": "ISC",    
  "dependencies": {    
    "body-parser": "^1.19.0",    
    "ejs": "^3.0.1",    
    "express": "^4.17.1",    
    "mongoose": "^5.8.11",    
    "qrcode": "^1.4.4"    
  }    
}  

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

var mongoose    =   require('mongoose');    
    
var userSchema  =   new mongoose.Schema({    
    name:{    
        type:String    
    },    
    phno:{    
        type:Number    
    }    
});    
    
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

<html lang="en">    
<head>    
    <meta charset="UTF-8">    
    <meta name="viewport" content="width=device-width, initial-scale=1.0">    
    <meta http-equiv="X-UA-Compatible" content="ie=edge">    
    <title>Qrcode</title>    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">    
</head>    
<body>    
    <div class="nav justify-content-center">    
    <div class="card border-primary mb-3" style="max-width: 18rem;margin-top: 20px;">    
        <div class="card-header">User Details</div>    
        <div class="card-body text-primary">    
            <form action="/" method="post">    
                <input type="text" name="name" placeholder="enter the name" class="form-control"><br>    
                <input type="text" name="phno" placeholder="enter the phone number" class="form-control"><br>    
               <div class="text-center"> <input type="submit" value="get qrcode" class="btn"> </div>     
             </form>    
        </div>    
      </div>    
    </div>    
    <%if(data){%>     
        <div class="text-center">    
         <h5>Scan QRCode</h5>    
        <img src="<%=data%>" alt="" style="width:100px; height:100px;">    
         </div>    
    <%}%>      
</body>    
</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

var express     =   require('express');    
var mongoose    =   require('mongoose');    
var userModel   =   require('./models/user');    
var bodyParser  =   require('body-parser');    
var QRCode      =   require('qrcode');    
    
//connect to db    
mongoose.connect('mongodb://localhost:27017/qrdemo',{useNewUrlParser:true})    
.then(()=>console.log('connected to db'))    
.catch((err)=>console.log(err))    
    
//init app    
var app = express();    
    
//set the template engine    
app.set('view engine','ejs');    
    
//fetch data from the reuqest    
app.use(bodyParser.urlencoded({extended:false}));    
    
//default page load    
app.get('/',(req,res)=>{    
       userModel.find((err,data)=>{    
          if(err){    
              console.log(err);    
          }else{    
              if(data!=''){    
                  var temp =[];    
                  for(var i=0;i< data.length;i++){    
                      var name = {    
                          data:data[i].name    
                      }    
                      temp.push(name);    
                      var phno = {    
                          data:data[i].phno    
                      }    
                      temp.push(phno);    
                  }   
                  // Returns a Data URI containing a representation of the QR Code image.  
                  QRCode.toDataURL(temp,{errorCorrectionLevel:'H'},function (err, url) {    
                    console.log(url)    
                    res.render('home',{data:url})    
                  });    
              }else{    
                  res.render('home',{data:''});    
              }    
          }    
       });    
});    
    
app.post('/',(req,res)=>{    
        var userr = new userModel({    
            name:req.body.name,    
            phno:req.body.phno    
        });    
        userr.save((err,data)=>{    
             if(err){    
                 console.log(err);    
             }else{    
                 res.redirect('/');    
             }    
        });    
});    
    
//assign port    
var port  = process.env.PORT || 3000;    
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:

{    
  "name": "qrcodee",    
  "version": "1.0.0",    
  "description": "",    
  "main": "index.js",    
  "scripts": {    
    "test": "echo \"Error: no test specified\" && exit 1",    
    "start": "node app.js"    
  },    
  "keywords": [],    
  "author": "",    
  "license": "ISC",    
  "dependencies": {    
    "body-parser": "^1.19.0",    
    "ejs": "^3.0.1",    
    "express": "^4.17.1",    
    "mongoose": "^5.8.11",    
    "qrcode": "^1.4.4"    
  }    
}    
  • Download the code here

Thanks for reading!

#node-js #qrcodes #tutorial #developer

How to Create and Read QR Code in Node.js
1 Likes168.70 GEEK