Open In App

Generate a QR code in Node.js

In this article, we will discuss how to generate a QR code using Node.js. A QR code is a monochromatic matrix with embedded data that is used in manufacturing industries in order to label the products. Nowadays QR codes are being used for payments in UPI-based apps, some chatting apps like WhatsApp, and in the play store. These are some most common examples, but we can use QR code in our apps for a far better purpose. If we are creating a website using MEAN/MERN Stack or any JavaScript related technology, We can generate QR codes in order to build advanced apps.

Let’s set up our workspace by executing these commands:



Creating directory:

npm init -y
mkdir src
cd src
nano app.js



Installing package: We need to install an npm package in order to work ahead.

npm install qrcode

There are two ways we can use this library to generate QR codes. The first one is used for development and testing. Another one is used for deployment.

let data = {
    name:"Employee Name",
    age:27,
    department:"Police",
    id:"aisuoiqu3234738jdhf100223"
}
// Converting into String data
let stringdata = JSON.stringify(data)

1. toString(text, [options], [cb(error, string)])

// Print the QR code to terminal
QRCode.toString(stringdata,{type:'terminal'}, function (err, url) {
   if(err) return console.log("error occurred")
   console.log(url)
 })

2. toDataURL(text, [options], [cb(error, url)])

// Get the base64 url
QRCode.toDataURL(stringdata, function (err, url) {
    if(err) return console.log("error occurred")
    console.log(url)
})

There is one additional toCanvas() method but its functionalities can be used within toDataURL() method.

Index.js




// Require the package
const QRCode = require('qrcode')
 
// Creating the data
let data = {
    name:"Employee Name",
    age:27,
    department:"Police",
    id:"aisuoiqu3234738jdhf100223"
}
 
// Converting the data into String format
let stringdata = JSON.stringify(data)
 
// Print the QR code to terminal
QRCode.toString(stringdata,{type:'terminal'},
                    function (err, QRcode) {
 
    if(err) return console.log("error occurred")
 
    // Printing the generated code
    console.log(QRcode)
})
   
// Converting the data into base64
QRCode.toDataURL(stringdata, function (err, code) {
    if(err) return console.log("error occurred")
 
    // Printing the code
    console.log(code)
})

Run index.js file using the following command:

node index.js

Output:


Article Tags :