QR code generator for both server-side and client-side applications with multiple output formats including PNG, SVG, Canvas, and Terminal rendering.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Server-only functions for saving QR codes to files, generating buffers, and streaming output. These functions are available only in Node.js environments and provide comprehensive file system integration.
Saves QR codes directly to image files with automatic format detection.
/**
* Saves QR Code to image file
* @param {string} path - File path to save to
* @param {string|Array} text - Text to encode or segments
* @param {Object} options - File and rendering options
* @param {Function} callback - Completion callback
* @returns {Promise} Promise when using async/await
*/
function toFile(path, text, options, callback);Usage Examples:
const QRCode = require('qrcode');
// Save as PNG (default)
QRCode.toFile('qrcode.png', 'Hello World', function (err) {
if (err) throw err;
console.log('QR code saved as PNG');
});
// Save as SVG
QRCode.toFile('qrcode.svg', 'Hello World', function (err) {
if (err) throw err;
console.log('QR code saved as SVG');
});
// Save as UTF-8 text
QRCode.toFile('qrcode.txt', 'Hello World', function (err) {
if (err) throw err;
console.log('QR code saved as text');
});
// Format detection from extension
QRCode.toFile('output.png', 'Hello World'); // PNG
QRCode.toFile('output.svg', 'Hello World'); // SVG
QRCode.toFile('output.txt', 'Hello World'); // UTF-8
// Explicit format specification
QRCode.toFile('output.png', 'Hello World', {
type: 'png',
width: 300,
color: {
dark: '#0000FF',
light: '#FFFFFF'
}
});
// Using Promises
try {
await QRCode.toFile('qr.png', 'Hello World', { width: 400 });
console.log('File saved successfully');
} catch (err) {
console.error('Save failed:', err);
}Generates QR codes as Node.js buffers for in-memory processing.
/**
* Generates QR code as Node.js Buffer
* @param {string|Array} text - Text to encode or segments
* @param {Object} options - Buffer generation options
* @param {Function} callback - Callback with (error, buffer)
* @returns {Promise<Buffer>} Buffer when using promises
*/
function toBuffer(text, options, callback);Usage Examples:
// Generate PNG buffer
QRCode.toBuffer('Hello World', function (err, buffer) {
if (err) throw err;
console.log('Buffer size:', buffer.length);
console.log('Buffer type:', typeof buffer); // 'object' (Buffer)
// Write buffer to file manually
require('fs').writeFileSync('manual.png', buffer);
});
// Generate SVG buffer
QRCode.toBuffer('Hello World', { type: 'svg' }, function (err, buffer) {
if (err) throw err;
// Convert to string for SVG
const svgString = buffer.toString('utf8');
console.log(svgString); // <svg xmlns="http://www.w3.org/2000/svg"...
});
// Generate UTF-8 text buffer
QRCode.toBuffer('Hello World', { type: 'utf8' }, function (err, buffer) {
if (err) throw err;
const textQR = buffer.toString('utf8');
console.log(textQR); // ASCII art QR code
});
// Custom PNG options
QRCode.toBuffer('Hello World', {
type: 'png',
width: 500,
rendererOpts: {
deflateLevel: 9, // Maximum compression
deflateStrategy: 3 // Default strategy
}
}, function (err, buffer) {
console.log('Compressed PNG buffer:', buffer.length, 'bytes');
});
// Using Promises
try {
const buffer = await QRCode.toBuffer('Hello World', { type: 'png' });
// Process buffer (send via HTTP, store in database, etc.)
console.log('Generated buffer:', buffer.length, 'bytes');
} catch (err) {
console.error('Buffer generation failed:', err);
}Writes QR codes directly to Node.js streams (PNG format only).
/**
* Writes QR Code to a writable stream (PNG only)
* @param {stream.Writable} stream - Destination stream
* @param {string|Array} text - Text to encode or segments
* @param {Object} options - Stream writing options
*/
function toFileStream(stream, text, options);Usage Examples:
const fs = require('fs');
const QRCode = require('qrcode');
// Write to file stream
const writeStream = fs.createWriteStream('stream-output.png');
QRCode.toFileStream(writeStream, 'Hello Stream World', {
width: 300,
color: { dark: '#FF0000' }
});
writeStream.on('finish', () => {
console.log('QR code written to stream');
});
writeStream.on('error', (err) => {
console.error('Stream error:', err);
});
// Write to HTTP response stream
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Disposition': 'attachment; filename="qrcode.png"'
});
QRCode.toFileStream(res, req.url.slice(1) || 'Default QR Code', {
width: 200
});
});
// Write to any writable stream
const { PassThrough } = require('stream');
const passThrough = new PassThrough();
QRCode.toFileStream(passThrough, 'Stream Data', { width: 250 });
passThrough.on('data', (chunk) => {
console.log('Received chunk:', chunk.length, 'bytes');
});
passThrough.on('end', () => {
console.log('Stream ended');
});PNG-specific options for file and buffer generation:
interface PNGOptions {
/** Output type */
type: 'png';
/** PNG-specific renderer options */
rendererOpts?: {
/** Deflate compression level (0-9) */
deflateLevel?: number; // Default: 9
/** Deflate compression strategy (0-3) */
deflateStrategy?: number; // Default: 3
};
}Examples:
// Maximum compression (slower, smaller files)
QRCode.toFile('compressed.png', 'text', {
type: 'png',
rendererOpts: {
deflateLevel: 9,
deflateStrategy: 3
}
});
// Fast compression (faster, larger files)
QRCode.toFile('fast.png', 'text', {
type: 'png',
rendererOpts: {
deflateLevel: 1,
deflateStrategy: 0
}
});
// No compression (fastest, largest files)
QRCode.toFile('uncompressed.png', 'text', {
type: 'png',
rendererOpts: {
deflateLevel: 0
}
});SVG files support all standard rendering options:
QRCode.toFile('styled.svg', 'SVG QR Code', {
type: 'svg',
width: 300,
margin: 2,
color: {
dark: '#000080',
light: '#FFFFFF'
}
});Text files support terminal rendering options:
QRCode.toFile('qr.txt', 'Text QR', {
type: 'utf8',
small: false, // Full-size terminal output
inverse: false // Normal colors
});The toFile() function automatically detects format from file extension:
// Recognized extensions and their formats
QRCode.toFile('qr.png', 'text'); // PNG format
QRCode.toFile('qr.svg', 'text'); // SVG format
QRCode.toFile('qr.txt', 'text'); // UTF-8 text format
// Override auto-detection
QRCode.toFile('qr.png', 'text', { type: 'svg' }); // Saves SVG despite .png extension
// Unknown extensions default to PNG
QRCode.toFile('qr.xyz', 'text'); // PNG formatServer operations can encounter file system and format-specific errors:
// File system errors
QRCode.toFile('/readonly/path.png', 'text', function (err) {
if (err) {
console.log(err.code); // 'EACCES', 'ENOENT', etc.
console.log(err.message); // File system error message
}
});
// Invalid path errors
QRCode.toFile('', 'text', function (err) {
if (err) {
console.log(err.message); // "Invalid argument"
}
});
// Stream errors
const badStream = fs.createWriteStream('/invalid/path.png');
QRCode.toFileStream(badStream, 'text');
badStream.on('error', (err) => {
console.log('Stream error:', err.message);
});
// Buffer generation errors
QRCode.toBuffer('text', { type: 'invalid' }, function (err, buffer) {
if (err) {
console.log(err.message); // Format-specific error
}
});const express = require('express');
const QRCode = require('qrcode');
const app = express();
// Generate QR code as response
app.get('/qr/:text', async (req, res) => {
try {
const buffer = await QRCode.toBuffer(req.params.text, {
width: 300,
type: 'png'
});
res.setHeader('Content-Type', 'image/png');
res.setHeader('Content-Length', buffer.length);
res.send(buffer);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Stream QR code directly to response
app.get('/qr-stream/:text', (req, res) => {
res.setHeader('Content-Type', 'image/png');
QRCode.toFileStream(res, req.params.text, { width: 250 });
});const fs = require('fs');
const path = require('path');
const QRCode = require('qrcode');
// Batch QR code generation
async function generateQRCodes(texts, outputDir) {
for (let i = 0; i < texts.length; i++) {
const text = texts[i];
const filename = path.join(outputDir, `qr_${i}.png`);
try {
await QRCode.toFile(filename, text, {
width: 300,
color: { dark: '#000080' }
});
console.log(`Generated: ${filename}`);
} catch (err) {
console.error(`Failed to generate ${filename}: ${err.message}`);
}
}
}
// Usage
generateQRCodes(['Hello', 'World', 'QR Codes'], './output/');const QRCode = require('qrcode');
// Store QR codes as binary data
async function storeQRCode(text, database) {
try {
const buffer = await QRCode.toBuffer(text, {
type: 'png',
width: 200
});
// Store buffer in database
await database.qrcodes.insert({
text: text,
image: buffer,
created: new Date()
});
console.log('QR code stored in database');
} catch (err) {
console.error('Database storage failed:', err);
}
}Install with Tessl CLI
npx tessl i tessl/npm-qrcode