How to Dynamically Generate and Decode a QR Code with NodeJs

qrcode download


In today's digital age, QR (Quick Response) codes have become vital for bridging the gap between the physical and digital domains. They provide a range of applications, covering everything from payment and verification to smooth information exchange. Node.js, a popular JavaScript runtime environment, allows developers to easily produce qrcode with nodejs. The development is pretty easy with qrcode npm. This technology is used in manufacturing for product labeling, UPI-based payment systems, chat systems such as WhatsApp, and even app distribution. QR codes provide a simple and effective means of storing and conveying data, making them extremely useful tools in current digital applications.

In this blog post, I will explain how to develop qrcode js generator in your application with an easy-to-understand qrcode example. 

Set up the Project

Before you start coding, make sure Node.js and npm are installed on your system. 

To begin a new Node.js project, first, create a new directory and change the directory to it using your terminal. Then, execute the following command. Use npm to install Express.js and a QR code generation library named qrcode.

   
    npm init -y
    npm install express qrcode


Install qrcode js npm

Install the qrcode pacakge by using the following command.

   
    npm install qrcode


Qrcode converter with nodeJs and expressJs

My data object contains information like name, age, department, and ID, which I am converting to a JSON string using `JSON.stringify`. When a GET request is made to '/generate-qrcode', it asynchronously converts the JSON string to a QR code data URI using qrcode to base64. It will generate the qrcode with image in an HTML `<img>` tag and send it as a response.

   
    const express = require('express');
    const QRCode = require('qrcode');

    const app = express();
    const port = 3000; // or any other port you prefer

    // this is the data I want to hide with QR code
    const data = {
        name: "codegirl",
        age: 27,
        department: "Software Development",
        id: "codegirl0101dev"
    };

    // I am defining a route to generate QR code
    app.get('/generate-qrcode', async (req, res) => {
        try {
            // Converting the data object to a JSON string woth stringify
            const jsonString = JSON.stringify(data);

            // Generating QR code as a data URI
            const qrCode = await QRCode.toDataURL(jsonString);

            // Sending QR code image of base64 as a response
            res.send(`<img src="${qrCode}" alt="QR Code">`);
        } catch (err) {
            console.error('Error generating QR code:', err);
            res.status(500).send('Failed to generate QR code');
        }
    });

    // Starting the node server
    app.listen(port, () => {
        console.log(`Server is running on http://localhost:${port}`);
    });



Run your App

Start your application by following command:

   
    node index.js


How to Decode Qrcode

For qrcode decoder, you need to install qrcode-reader and multer to capture the buffer.


  npm install qrcode-reader jimp multer



Qrcode Reader - Qrcode Data Decode with Image

What I did here is pretty simple. I first checked if the given request was a file type or not. If not, it responds with a 400 status and a message indicating no file was uploaded. I used Jimp library - qrcode library for decode, to read the uploaded image from req.file.buffer. If decoding is successful, it responds with the decoded QR code data as a JSON object.



    const express = require('express');
    const QRCode = require('qrcode');
    const Jimp = require('jimp');
    const QrCodeReader = require('qrcode-reader');
    const multer = require('multer');
    const path = require('path');
   
    const app = express();
    const port = 3000;
   
    const storage = multer.memoryStorage();
    const upload = multer({ storage: storage });
   
    const data = {
        name: "codegirl",
        age: 27,
        department: "Software Development",
        id: "codegirl0101dev"
    };
   
    app.get('/generate-qrcode', async (req, res) => {
        try {
            const jsonString = JSON.stringify(data);
   
            const qrCode = await QRCode.toDataURL(jsonString);
              res.send(`<img src="${qrCode}" alt="QR Code">`);
        } catch (err) {
            console.error('Error generating QR code:', err);
            res.status(500).send('Failed to generate QR code');
        }
    });
   
    app.post('/decode-qrcode', upload.single('qrcode'), async (req, res) => {
        try {
            if (!req.file) {
                return res.status(400).send('No file uploaded');
            }
   
            const image = await Jimp.read(req.file.buffer);
              const qr = new QrCodeReader();
   
            qr.callback = (err, value) => {
                if (err) {
                    console.error('Error decoding QR code:', err);
                    return res.status(500).send('Failed to decode QR code');
                }
   
                res.json(value.result);
            };
   
            qr.decode(image.bitmap);
        } catch (err) {
            console.error('Error processing QR code image:', err);
            res.status(500).send('Failed to process QR code image');
        }
    });
   
    app.listen(port, () => {
        console.log(`Server is running on http://localhost:${port}`);
    });
 


That's it! You have successfully developed qrcode barcode generator with nodeJs.


Frequently Asked Questions

Why I am getting Uncaught TypeError: QrCode is not a constructor error?

The error "Uncaught TypeError: QrCode is not a constructor" happens when you try to use a function or object as a constructor (using new).

What are some best qrcode with logo npm?

  • qrcode-with-logos
  • react-qrcode-logo

Are qrcode and barcode same?

While both QR codes and barcodes are ways of encoding data for scanning and identification, QR codes are more versatile in terms of the type and amount of data they can encode, as well as having a unique visual look when compared to regular linear barcodes.

codegirl

Hello, I’m Sangita, person behind "codegirl", a dedicated web developer. Crafting digital experiences is not just my job; it’s my passion. Let’s build something exceptional together!

Post a Comment

Previous Post Next Post