code icon Code

Generate QR Code

Generate QR code images from data

Source Code

import fs from "fs";
import path from "path";
import QRCode from "qrcode";

const [data, outputPath, optionsJson = "{}"] = process.argv.slice(2);

if (!data || !outputPath) {
  console.error("Usage: data outputPath [options]");
  process.exit(1);
}

try {
  console.log(`Generating QR code...`);
  console.log(`  Data: ${data.slice(0, 50)}${data.length > 50 ? "..." : ""}`);

  let options;
  try {
    options = JSON.parse(optionsJson);
  } catch {
    console.error("Invalid options JSON:", optionsJson);
    process.exit(1);
  }

  // Set defaults
  const qrOptions = {
    width: options.width || 300,
    margin: options.margin ?? 2,
    color: {
      dark: options.color?.dark || "#000000",
      light: options.color?.light || "#ffffff",
    },
    errorCorrectionLevel: options.errorCorrection || "M",
  };

  // Ensure output directory exists
  const dir = path.dirname(outputPath);
  if (dir && dir !== ".") {
    fs.mkdirSync(dir, { recursive: true });
  }

  // Determine output format from extension
  const ext = path.extname(outputPath).toLowerCase();

  if (ext === ".svg") {
    const svg = await QRCode.toString(data, { type: "svg", ...qrOptions });
    fs.writeFileSync(outputPath, svg);
  } else if (ext === ".txt" || ext === ".terminal") {
    const text = await QRCode.toString(data, { type: "terminal", ...qrOptions });
    fs.writeFileSync(outputPath, text);
  } else {
    // Default to PNG
    await QRCode.toFile(outputPath, data, qrOptions);
  }

  const stats = fs.statSync(outputPath);

  console.log(`\nāœ“ Generated QR code`);
  console.log(`  Size: ${qrOptions.width}px`);
  console.log(`  Format: ${ext || ".png"}`);
  console.log(`  File size: ${(stats.size / 1024).toFixed(1)} KB`);
  console.log(`  Written to: ${outputPath}`);

  console.log(
    JSON.stringify({
      success: true,
      data: data.slice(0, 100),
      outputPath,
      width: qrOptions.width,
      format: ext || ".png",
      fileSize: stats.size,
    })
  );
} catch (error) {
  console.error("Error:", error.message);
  process.exit(1);
}