![]() |
VOOZH | about |
Generating QR Code in Node can be helpful in sharing the url, images, text, and other data. A QR code is a monochromatic matrix with embedded data that is used in manufacturing industries in order to label 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.
In this article, we will discuss how to generate a QR code using Node.js.
To generate QR code in Node application we will we using the qrcode npm package. We will pass the data to the QRCode.toString method to generate the QR code for that data. We can also use the QRCode.toDataUrl to generate the required QR code
Use this command in the project directory to initialize a node js project
npm init -yLet's set up our workspace by executing these commands:
nano index.jsWe need to install an npm package named qrcode as the project dependency.
npm install qrcodeThere 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's create the data that we want to hide in a QR code:
let data = {
name:"Employee Name",
age:27,
department:"Police",
id:"aisuoiqu3234738jdhf100223"
}We need to convert data into a String format using JSON.stringify() method so that further operations can be performed easily.
// Converting into String data
let stringdata = JSON.stringify(data)Two methods of qrcode package are used for encoding the data. The first method will print the code in the terminal itself. But this method will be useless for deployment. But it is good for testing purposes.
// Print the QR code to terminal
QRCode.toString(stringdata,{type:'terminal'}, function (err, url) {
if(err) return console.log("error occurred")
console.log(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.
Run index.js file using the following command:
node index.jsOutput: