How to Generate QR Code in Node JS Application
In this article, we will explain to you how to generate QR code in node js application. They are usually used to encode a URL so that someone can simply scan the code and visit a site.
A QR code (Quick Response Code) is a machine-readable optical identifier that can include information about the item to which the code is attached.
Node Js Application Setup
First, we will open the command prompt and create the application in our directory. for this, you can follow the below command.
1 2 3 | mkdir my_node_app cd my_node_app npm init |
Install NPM Package
After the done setup node js application, we will install the express and qrcode npm package. so you can see the following npm command.
1 2 | npm install express --save npm install qrcode --save |
server.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | var express=require('express'); var app = express(); var QRCode = require('qrcode'); app.get('/',function(req,res){ // Creating the data let data = { name:"test", age:27, } // 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"); }else{ // 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"); }else{ // Printing the code console.log(code); } }) }); app.listen(3000,function(){ console.log("Express Started on Port 3000"); }); |
Run Node js Application
we will run the node js application using the below command. so you can follow the below command.
1 | node server.js |
Now you can run the example using the below Url in the browser.
1 | http://localhost:3000 |