Reading QR codes using Node.js
When we are working with Node.js to build any application, we might want our apps to interact with external apps or payment gateways that provide QR codes to communicate the information. In this article, we will see how we can decode a QR code in our node.js applications.
Let’s set up our workspace by executing these commands:
Creating directory:
npm init -y mkdir src cd src nano app.js
Installing packages:
We need to install an npm package in order to work ahead.
To work with the qrcode-reader, we also need an image parser. Jimp Module is used for image parsing.
npm install qrcode-reader jimp
Suppose we have an image of a QR code in the same directory as our source code. We need the data embedded in the image.
- First import all the packages in app.js
var Jimp = require("jimp"); var fs = require('fs') var QrCode = require('qrcode-reader');
- Now we need to load our QR code:
// Read the image and create a buffer // (Here image.png is our QR code) var buffer = fs.readFileSync(__dirname + '/image.png');
- Parse the image using Jimp module and use decode() method of qrcode-reader package:
// Parse the image Jimp.read(buffer, function(err, image) { if (err) { console.error(err); } let qrcode = new qrCode(); qrcode.callback = function(err, value) { if (err) { console.error(err); } console.log(value.result); }; qrcode.decode(image.bitmap); });
Here we can read the data that is in string format.
Index.js
Javascript
//Importing jimp module var Jimp = require( "jimp" ); // Importing filesystem module var fs = require( 'fs' ) // Importing qrcode-reader module var qrCode = require( 'qrcode-reader' ); // Read the image and create a buffer // (Here image.png is our QR code) var buffer = fs.readFileSync(__dirname + '/image.png' ); // Parse the image using Jimp.read() method Jimp.read(buffer, function (err, image) { if (err) { console.error(err); } // Creating an instance of qrcode-reader module let qrcode = new qrCode(); qrcode.callback = function (err, value) { if (err) { console.error(err); } // Printing the decrypted value console.log(value.result); }; // Decoding the QR code qrcode.decode(image.bitmap); }); |
Run index.js file using the following command:
node index.js
Output:

Output data
Please Login to comment...