Generating a QR code in Node.js is simple and fast thanks to libraries like qrcode
. In this guide, I’ll show you how to do it in just a few steps.
1. Initialize a New Node.js Project
Open the terminal, create a new folder, and initialize a project:
mkdir qr-code-generator
cd qr-code-generator
npm init -y
2. Install the qrcode
Library
Install the qrcode
library via npm:
npm install qrcode
3. Create the Script to Generate the QR Code
Now create a file called generate.js
with the following content:
const QRCode = require('qrcode');
const textToEncode = 'https://example.com';
QRCode.toFile('qrcode.png', textToEncode, {
color: {
dark: '#000', // Code color
light: '#FFF' // Background
}
}, function (err) {
if (err) throw err;
console.log('QR code successfully generated in qrcode.png');
});
4. Run the Script
Run the script in the terminal:
node generate.js
After execution, you’ll find the qrcode.png
file in the same folder. This file contains the QR code pointing to https://example.com
.
Conclusion
Using Node.js to generate QR codes is useful for automating code creation in web projects, desktop applications, or backend systems. The qrcode
library also supports generation in SVG or base64 format, offering flexibility for different needs.