How to generate QR Code using Node.js ?

Genrating QR codes is easy!!!

How to generate QR Code using Node.js ?

In today's blog, I'll show you how to use node package "qrcode" to generate QR codes.

Nowadays QR codes are used very extensively for payments through UPI, also chat apps like Whatsapp, to track shipping orders.

Step 1: First setup initial workspace by executing following command

npm init -y

Step 2: install qrcode package via npm

npm install --save qrcode

Step 3: Import qrcode package in app.js file

//app.js
const QRCode = require('qrcode')

Step 4: Create data that you want to convert to QR Code

//app.js
const dataString = "Sample Data"

Step 5: Now for converting data to QR code, we have multiple methods.

1. toDataURL(text, [options], [cb(error, URL)])

It will return Data URI containing a representation of the QR Code image

//app.js
const QRCode = require('qrcode')

//Data to be converted to QRcode
const dataString = "Sample Data"

// this method will convert data to base64
QRCode.toDataURL(dataString, function (err, url) {
        if(err) throw err

        // generated QR code
        console.log(url)
})

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

It will return a string representation of the QR Code.

//app.js
const QRCode = require('qrcode')

//Data to be converted to QRcode
const dataString = "Sample Data"

// this method will convert data to base64
QRCode.toString(dataString, function (err, url) {
        if(err) throw err

        // generated QR code in string format
        console.log(url)
})

There are other methods also like toCanvas(draws qrcode), toFile(save qrcode to image file). you can explore more on qrcode docs.

This was all about this blog, I hope it is useful for you. I'll see you in the next blog.