Skip to main content

How to Create and Read QR Code in Node.js

Introduction

In this post, you will learn how to Create a QR code in Node. 

Project Structure

This is image title

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"    
  }    
}    

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...