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
const Jimp = require("jimp");
const fs = require('fs')
const 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)
const buffer = fs.readFileSync(__dirname + '/image.png');
- Parse the image using the Jimp module and use the decode() method of the 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
const Jimp = require( "jimp" );
const fs = require( 'fs' )
const qrCode = require( 'qrcode-reader' );
const buffer = fs.readFileSync(__dirname + '/image.png' );
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);
});
|
Run the index.js file using the following command:
node index.js
Output:
Output data
Last Updated :
05 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...