QR Code generator using Node.js

QR Code generator using Node.js

QR codes have become an integral part of our digital lives from sharing links to contactless payments. Have you ever wondered how you can create a QR code generator using nodejs? Here we will walk you through explaining its purpose and functionality. By the end of this blog, you will have a solid understanding of how to build a QR code generator from scratch with not much knowledge of node js and npm.

Prerequisites

Before we begin make sure to have the following prerequisite :

  • Node.js: If you haven't already downloaded it, install it from here.

    That's all for now.

Code Overview

import inquirer from 'inquirer'
import qr from 'qr-image';
import fs from 'fs';

inquirer
  .prompt([
    {
        message:'Enter the URL:',
        name:"URL",
    },
  ])
  .then((answers) => {
    const url = answers.URL;
    let qr_svg = qr.image(url);
    qr_svg.pipe(fs.createWriteStream('qr_image2.png'));
    fs.writeFile('url2.txt', 'URL is of Wikipedia!!!', (err) => {
    if (err) throw err;
    console.log('The file has been saved!');
    }); 
  })
  .catch((error) => {
    if (error.isTtyError) {
      // Prompt couldn't be rendered in the current environment
    } else {
      // Something else went wrong
    }
  });

Gathering User Input

We start by importing three crucial Node.js packages :

  • `inquirer` is used to prompt the user for input.

  • `qr-image` allows us to generate QR code images.

  • `fs` is for working with the file system.

Generating the QR Code

Next, we generate the QR code image. We use qr.image(url) from the package, passing in the user's URL. This creates a QR Code image in memory.

To save the image, we pipe it to a writable stream created with fs.createWriteStream('qr_image2.png') saving it as a 'qr-image2.png' in the current directory.

Saving User Input

We use the built-in 'fs' module to create a text file named 'url2.txt' and save the text "URL is of Wikipedia" to it.

Error Handling

Code includes error handling in the form of a '.catch( )' block. It checks for potential errors like issues rendering prompts in the current environment etc.

Conclusion

It is just the overview of the project, you have to read the documentation yourself from nodejs and npm websites. Also, you can expand upon this code to create a more versatile QR code generator and enhance your error handling. Hope it helped you, do like and share with your friends.