CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-qrcode

QR code generator for both server-side and client-side applications with multiple output formats including PNG, SVG, Canvas, and Terminal rendering.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

string-rendering.mddocs/

String Output Rendering

String-based QR code rendering functionality that generates QR codes in multiple text and markup formats including UTF-8, SVG, and terminal output.

Note: In browser environments, toString only supports SVG output format. UTF-8 and terminal output formats are available only in Node.js environments.

Capabilities

String Output Generation

Generates string representations of QR codes in various formats.

/**
 * Returns a string representation of the QR Code
 * @param {string|Array} text - Text to encode or segments
 * @param {Object} options - String rendering options
 * @param {Function} callback - Callback with (error, string)
 * @returns {Promise<string>} String when using promises
 */
function toString(text, options, callback);

Usage Examples:

const QRCode = require('qrcode');

// UTF-8 text output (default)
QRCode.toString('Hello World', function (err, string) {
  if (err) throw err;
  console.log(string);
  // Outputs ASCII art representation:
  // █████████████████████████████
  // █████████████████████████████
  // ████ ▄▄▄▄▄ █▀▄█▀█ ▄▄▄▄▄ ████
  // ████ █   █ █▄▀▀▀▄█ █   █ ████
  // ...
});

// SVG output
QRCode.toString('Hello World', { type: 'svg' }, function (err, string) {
  if (err) throw err;
  console.log(string);
  // Outputs complete SVG markup:
  // <svg xmlns="http://www.w3.org/2000/svg" version="1.1" ...
});

// Terminal output (colorized for terminals)
QRCode.toString('Hello World', { type: 'terminal' }, function (err, string) {
  if (err) throw err;
  console.log(string);
  // Outputs terminal-optimized representation with ANSI colors
});

// Using Promises
try {
  const svgString = await QRCode.toString('Hello World', { type: 'svg' });
  const textString = await QRCode.toString('Hello World', { type: 'utf8' });
  const terminalString = await QRCode.toString('Hello World', { type: 'terminal' });
} catch (err) {
  console.error(err);
}

Output Format Types

UTF-8 Text Output

Plain text representation using Unicode block characters.

interface UTF8Options {
  /** Output format */
  type: 'utf8';
  /** Standard rendering options apply */
  margin?: number;
  scale?: number;
  small?: boolean;  // Compact output (terminal renderer only)
  inverse?: boolean; // Invert colors (terminal renderer only)
}

Examples:

// Standard UTF-8 output
const textQR = await QRCode.toString('Hello', { type: 'utf8' });
console.log(textQR);
// █████████████████████████████
// █████████████████████████████  
// ████ ▄▄▄▄▄ █▀▄█▀█ ▄▄▄▄▄ ████
// ████ █   █ █▄▀▀▀▄█ █   █ ████
// ████ █▄▄▄█ ██▄▀▀▄█ █▄▄▄█ ████

// Compact UTF-8 output
const compactQR = await QRCode.toString('Hello', { 
  type: 'utf8',
  small: true 
});
// Smaller representation using different Unicode characters

SVG Output

Complete SVG markup for web and vector graphics use.

interface SVGOptions {
  /** Output format */
  type: 'svg';
  /** SVG-specific options */
  width?: number;   // SVG width
  margin?: number;  // Quiet zone margin
  color?: {
    dark?: string;  // Dark module color
    light?: string; // Light module color  
  };
}

Examples:

// Basic SVG
const svgString = await QRCode.toString('Hello World', { type: 'svg' });
// <svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 25 25">
// <rect width="25" height="25" fill="#ffffff"/>
// <rect x="0" y="0" width="1" height="1" fill="#000000"/>
// ...
// </svg>

// Styled SVG
const styledSVG = await QRCode.toString('Styled QR', {
  type: 'svg',
  width: 300,
  margin: 4,
  color: {
    dark: '#0066CC',
    light: '#FFFFFF'
  }
});

// SVG with transparent background
const transparentSVG = await QRCode.toString('Transparent', {
  type: 'svg',
  color: {
    dark: '#000000',
    light: '#00000000'  // Transparent background
  }
});

Terminal Output

Terminal-optimized output with ANSI color support.

interface TerminalOptions {
  /** Output format */
  type: 'terminal';
  /** Terminal-specific options */
  small?: boolean;   // Compact terminal output
  inverse?: boolean; // Invert foreground/background colors
}

Examples:

// Standard terminal output
const terminalQR = await QRCode.toString('Terminal QR', { 
  type: 'terminal' 
});
console.log(terminalQR);
// Outputs with ANSI escape codes for proper terminal display

// Compact terminal output
const smallQR = await QRCode.toString('Small QR', {
  type: 'terminal',
  small: true
});

// Inverted colors
const invertedQR = await QRCode.toString('Inverted', {
  type: 'terminal',
  inverse: true
});

Browser Usage

SVG in Web Pages

// Generate SVG for web display
QRCode.toString('Web QR Code', { type: 'svg' }, function (err, svgString) {
  if (err) throw err;
  
  // Insert directly into DOM
  document.getElementById('qr-container').innerHTML = svgString;
  
  // Or create SVG element
  const parser = new DOMParser();
  const svgDoc = parser.parseFromString(svgString, 'image/svg+xml');
  const svgElement = svgDoc.documentElement;
  document.body.appendChild(svgElement);
});

// Styled SVG for web
QRCode.toString('Styled Web QR', {
  type: 'svg',
  width: 250,
  color: {
    dark: '#2E8B57',    // Sea green
    light: '#F0F8FF'    // Alice blue
  }
}, function (err, svgString) {
  document.getElementById('styled-qr').innerHTML = svgString;
});

React Integration

import React, { useState, useEffect } from 'react';
import QRCode from 'qrcode';

function SVGQRCode({ text, options = {} }) {
  const [svgString, setSvgString] = useState('');
  
  useEffect(() => {
    QRCode.toString(text, { type: 'svg', ...options })
      .then(setSvgString)
      .catch(console.error);
  }, [text, options]);
  
  return (
    <div 
      dangerouslySetInnerHTML={{ __html: svgString }} 
      style={{ display: 'inline-block' }}
    />
  );
}

// Usage
<SVGQRCode 
  text="React QR Code" 
  options={{ 
    width: 200, 
    color: { dark: '#FF6B6B', light: '#4ECDC4' } 
  }} 
/>

Vue Integration

// Vue component using SVG string
export default {
  props: ['text', 'options'],
  data() {
    return {
      svgString: ''
    };
  },
  watch: {
    text: 'generateQR',
    options: 'generateQR'
  },
  mounted() {
    this.generateQR();
  },
  methods: {
    async generateQR() {
      try {
        this.svgString = await QRCode.toString(this.text, {
          type: 'svg',
          ...this.options
        });
      } catch (err) {
        console.error(err);
      }
    }
  },
  template: `<div v-html="svgString"></div>`
};

Node.js Usage

CLI Applications

#!/usr/bin/env node
const QRCode = require('qrcode');

// Terminal QR code display
async function displayQR(text) {
  try {
    const qrString = await QRCode.toString(text, { 
      type: 'terminal',
      small: process.stdout.columns < 80  // Adapt to terminal width
    });
    console.log(qrString);
  } catch (err) {
    console.error('QR generation failed:', err.message);
  }
}

// Usage: node qr-display.js "Hello World"
displayQR(process.argv[2] || 'Default Text');

File Generation

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

// Generate SVG file
async function generateSVGFile(text, filename) {
  try {
    const svgString = await QRCode.toString(text, {
      type: 'svg',
      width: 400,
      margin: 2
    });
    
    fs.writeFileSync(filename, svgString, 'utf8');
    console.log(`SVG QR code saved to ${filename}`);
  } catch (err) {
    console.error('SVG generation failed:', err);
  }
}

// Generate text file  
async function generateTextFile(text, filename) {
  try {
    const textString = await QRCode.toString(text, { type: 'utf8' });
    
    fs.writeFileSync(filename, textString, 'utf8');
    console.log(`Text QR code saved to ${filename}`);
  } catch (err) {
    console.error('Text generation failed:', err);
  }
}

// Usage
generateSVGFile('SVG QR Code', 'qr.svg');
generateTextFile('Text QR Code', 'qr.txt');

Email Templates

const QRCode = require('qrcode');

// Generate SVG for HTML email
async function generateEmailQR(url, options = {}) {
  try {
    const svgString = await QRCode.toString(url, {
      type: 'svg',
      width: 150,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      },
      ...options
    });
    
    // SVG can be embedded directly in HTML emails
    return `
      <div style="text-align: center;">
        <p>Scan to visit:</p>
        ${svgString}
        <p><a href="${url}">${url}</a></p>
      </div>
    `;
  } catch (err) {
    console.error('Email QR generation failed:', err);
    return `<p>QR Code generation failed</p>`;
  }
}

Advanced String Rendering

Custom Styling

// High-contrast SVG for accessibility
const accessibleQR = await QRCode.toString('Accessible QR', {
  type: 'svg',
  width: 300,
  margin: 4,
  color: {
    dark: '#000000',    // Pure black
    light: '#FFFFFF'    // Pure white
  }
});

// Branded SVG with custom colors
const brandedQR = await QRCode.toString('Brand QR', {
  type: 'svg', 
  width: 250,
  color: {
    dark: '#FF6B35',    // Brand orange
    light: '#F7F7F7'    // Light gray
  }
});

Multiple Format Generation

// Generate all formats for the same data
async function generateAllFormats(text) {
  const formats = ['utf8', 'svg', 'terminal'];
  const results = {};
  
  for (const format of formats) {
    try {
      results[format] = await QRCode.toString(text, { type: format });
    } catch (err) {
      results[format] = `Error: ${err.message}`;
    }
  }
  
  return results;
}

// Usage
const allFormats = await generateAllFormats('Multi-format QR');
console.log('UTF-8:', allFormats.utf8);
console.log('SVG length:', allFormats.svg.length);
console.log('Terminal output ready:', allFormats.terminal.includes('\x1b'));

Error Handling

String rendering functions handle format-specific errors:

// Invalid format type
QRCode.toString('text', { type: 'invalid' }, function (err, string) {
  if (err) {
    console.log(err.message); // Format-specific error
  }
});

// Data too large for string rendering
QRCode.toString('x'.repeat(8000), { type: 'svg' }, function (err, string) {
  if (err) {
    console.log(err.message); // "The amount of data is too big..."
  }
});

// Terminal-specific errors
QRCode.toString('text', { 
  type: 'terminal', 
  invalidOption: true 
}, function (err, string) {
  if (err) {
    console.log(err.message); // Option validation error
  }
});

Install with Tessl CLI

npx tessl i tessl/npm-qrcode

docs

browser-rendering.md

configuration.md

core-generation.md

index.md

server-operations.md

string-rendering.md

tile.json