Welcome folks today in this blog post we will be generating qr codes
in node.js and javascript using qrcode
library. All the full source code of application is given below.
Get Started
In order to get started you need to install the qrcode
library globally inside your node.js application by executing the below command
npm i -g qrcode
After executing this command you can generate simple qr codes
using the below command
qrcode "some text"
You can see that it generates instantly the qr code
in the console.
Now you can also provide additional parameter of color of qr code
in the below command to generate colored qr codes
qrcode -d F00 -o out.png "sample text"
Now in the command you will see two additional parameters been added
-d
stands for dark color of qr code as foreground here we are providing the qr code
of red
-o
stands for output file and we have name of out.png
file
If you execute this command you will see the following result
Browser Usage
You can use this node-qrcode
library in the browser side as shown below
1 2 3 4 5 6 7 |
<!-- index.html --> <html> <body> <canvas id="canvas"></canvas> <script src="bundle.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 |
// index.js -> bundle.js var QRCode = require('qrcode') var canvas = document.getElementById('canvas') QRCode.toCanvas(canvas, 'sample text', function (error) { if (error) console.error(error) console.log('success!'); }) |
1 2 3 4 5 6 7 8 9 |
<canvas id="canvas"></canvas> <script src="/build/qrcode.min.js"></script> <script> QRCode.toCanvas(document.getElementById('canvas'), 'sample text', function (error) { if (error) console.error(error) console.log('success!'); }) </script> |
Node.js Usage
You can also use this library as a standalone application inside node.js as shown below
npm i qrcode
After installing this inside node.js project you need to make an index.js
file and copy paste the following code
index.js
1 2 3 4 5 |
var QRCode = require('qrcode') QRCode.toDataURL('I am a pony!', function (err, url) { console.log(url) }) |
Now if you execute this node.js project it will convert the text to base64 string url
as shown below
Now if you want to generate the qr code
inside node.js with the help of this library you can copy paste the following code which is given below
1 2 3 4 5 |
var QRCode = require('qrcode') QRCode.toString('I am a pony!',{type:'terminal'}, function (err, url) { console.log(url) }) |