Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Generate vCard (VCF) Contact Files in Node.js ?
Next article icon

Generate a QR code in Node.js

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Generating QR Code in Node can be helpful in sharing the url, images, text, and other data. A QR code is a monochromatic matrix with embedded data that is used in manufacturing industries in order to label products. Nowadays QR codes are being used for payments in UPI-based apps, some chatting apps like WhatsApp, and in the play store. These are some most common examples, but we can use QR code in our apps for a far better purpose.

In this article, we will discuss how to generate a QR code using Node.js.

Approach

To generate QR code in Node application we will we using the qrcode npm package. We will pass the data to the QRCode.toString method to generate the QR code for that data. We can also use the QRCode.toDataUrl to generate the required QR code

Steps to Generate QR Code in Node

Step 1: Initialize Node app

Use this command in the project directory to initialize a node js project

npm init -y

Step 2: Create index.js

Let’s set up our workspace by executing these commands:

nano index.js

Step 3: Installing Required Package

We need to install an npm package named qrcode as the project dependency.

npm install qrcode

Step 4: Create Data and Convert to String

There are two ways we can use this library to generate QR codes. The first one is used for development and testing. Another one is used for deployment.

Let’s create the data that we want to hide in a QR code:

let data = {     name:"Employee Name",     age:27,     department:"Police",     id:"aisuoiqu3234738jdhf100223" }

We need to convert data into a String format using JSON.stringify() method so that further operations can be performed easily.

// Converting into String data let stringdata = JSON.stringify(data)

Step 5: Generate QR code

Two methods of qrcode package are used for encoding the data. The first method will print the code in the terminal itself. But this method will be useless for deployment. But it is good for testing purposes.

1. toString(text, [options], [cb(error, string)])

// Print the QR code to terminal QRCode.toString(stringdata,{type:'terminal'}, function (err, url) {    if(err) return console.log("error occurred")    console.log(url)  })

2. toDataURL(text, [options], [cb(error, url)])

// Get the base64 url QRCode.toDataURL(stringdata, function (err, url) {     if(err) return console.log("error occurred")     console.log(url) })

There is one additional toCanvas() method but its functionalities can be used within toDataURL() method.

JavaScript
// Filename - index.js  // Require the package const QRCode = require('qrcode')  // Creating the data let data = {     name:"Employee Name",     age:27,     department:"Police",     id:"aisuoiqu3234738jdhf100223" }  // Converting the data into String format let stringdata = JSON.stringify(data)  // Print the QR code to terminal QRCode.toString(stringdata,{type:'terminal'},                     function (err, QRcode) {      if(err) return console.log("error occurred")      // Printing the generated code     console.log(QRcode) })    // Converting the data into base64  QRCode.toDataURL(stringdata, function (err, code) {     if(err) return console.log("error occurred")      // Printing the code     console.log(code) }) 

Step 6: Run the Application

Run index.js file using the following command:

node index.js

Output:



Next Article
How to Generate vCard (VCF) Contact Files in Node.js ?

M

mukulbindal170299
Improve
Article Tags :
  • JavaScript
  • Node.js
  • Web Technologies
  • Node.js-Misc

Similar Reads

  • How to generate short id in Node.js ?
    In this article we are going to see how to generate a short id in Node.js. There is an NPM package called ‘shortid’ used to create short non-sequential url-friendly unique ids. By default, it uses 7-14 url-friendly characters: A-Z, a-z, 0-9, _-. It Supports cluster (automatically), custom seeds, cus
    1 min read
  • QR Code Generator Service with Node.js and Express.js
    Nowadays, Quick Response (QR) codes have become an integral tool for transferring information quickly and conveniently. This project aims to develop a QR code generation API service using Node.js and Express.js. In addition, it goes further and extends the former by providing more customization opti
    5 min read
  • How to Generate vCard (VCF) Contact Files in Node.js ?
    vCard (VCF) files are a widely used format for storing and exchanging contact information. They are supported by various applications and devices, making them a convenient way to share contact details. In Node.js, you can easily generate vCard files using different libraries and techniques. This art
    4 min read
  • Generate QR code using AngularJS
    In this article, we will see how to generate and display QR codes in our Angular apps. A QR code is a matrix of black and white squares that can be read by a camera or a smartphone. A QR code can store information and URLs that make it easy to read for a bot or smartphone user. In a business scenari
    3 min read
  • Node.js ecdh.generateKeys() Method
    The ecdh.generateKeys() method is an inbuilt application programming interface of class ECDH within the crypto module which is used to generate private and public key values of the Elliptic Curve Diffie-Hellman (ECDH) object. It returns only the public key in the given format and encoding. Syntax: e
    3 min read
  • Encrypting Data in Node.js
    Encryption and Decryption in Node can be done by installing and implementing the 'crypto' library. If you have installed Node.js by manual build, then there is a chance that the crypto library is not shipped with it. You can run the following command to install the crypto dependency. npm install cry
    1 min read
  • How to make a QR Code generator using qrcode.js ?
    Modern web applications require generating QR codes for certain features where we need to enable a convenient way of data sharing like QR codes for the end users. Some popular QR codes use cases are UPI payment addresses, invoice details, contact cards, web links, etc. QR(Quick Response) code is a m
    6 min read
  • Node.js crypto.generateKeyPair() Method
    The crypto.generateKeyPair() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if option's
    4 min read
  • How to generate unique ID with node.js?
    In this article, we are going to learn how to generate a unique ID using Node.js. Unique ID means a string contains a unique identity throughout the program. Table of Content Using UUIDUsing CryptoPrerequisitesJavaScript Node JSApproach 1: Using UUIDUUID is a module of NPM (Node Package Manager). UU
    1 min read
  • Node.js crypto.generateKeyPairSync() Method
    The crypto.generateKeyPairSync() method is an inbuilt application programming interface of crypto module which is used to generate a new asymmetric key pair of the specified type. For example, the currently supported key types are RSA, DSA, EC, Ed25519, Ed448, X25519, X448, and DH. Moreover, if opti
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences