CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-figlet

Creates ASCII Art from text with a full implementation of the FIGfont specification

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

font-management.mddocs/

Font Management

Comprehensive font loading, listing, and management system supporting both browser and Node.js environments with built-in font discovery and custom font parsing capabilities.

Capabilities

Asynchronous Font Loading

Load fonts dynamically with automatic caching and cross-platform support.

/**
 * Loads a font asynchronously from the font directory
 * @param name - Font name (without .flf extension)
 * @param callback - Optional callback function (err, fontOptions) => void
 * @returns Promise<object> - Font configuration object
 */
function loadFont(name, callback);

Usage Examples:

const figlet = require("figlet");

// Promise-based loading
const fontOptions = await figlet.loadFont("Ghost");
console.log("Font loaded:", fontOptions);

// Callback-based loading
figlet.loadFont("Big", (err, fontOptions) => {
  if (err) {
    console.error("Font loading failed:", err);
    return;
  }
  console.log("Font height:", fontOptions.height);
  console.log("Font baseline:", fontOptions.baseline);
});

// Load multiple fonts
const fonts = ["Standard", "Big", "Ghost", "Larry 3D"];
for (const fontName of fonts) {
  await figlet.loadFont(fontName);
}

Synchronous Font Loading

Load fonts synchronously using filesystem access (Node.js only).

/**
 * Loads a font synchronously from filesystem (Node.js only)
 * @param name - Font name (without .flf extension)
 * @returns object - Font configuration object
 * @throws Error if font file cannot be read or parsed
 */
function loadFontSync(name);

Usage Examples:

// Basic synchronous loading
try {
  const fontOptions = figlet.loadFontSync("Standard");
  console.log("Font loaded with height:", fontOptions.height);
} catch (err) {
  console.error("Failed to load font:", err.message);
}

// Preload fonts for synchronous text generation
const requiredFonts = ["Big", "Ghost", "Larry 3D"];
const fontConfigs = {};

for (const fontName of requiredFonts) {
  try {
    fontConfigs[fontName] = figlet.loadFontSync(fontName);
  } catch (err) {
    console.warn(`Could not load font ${fontName}:`, err.message);
  }
}

Font Discovery

List all available fonts in the font directory (Node.js only).

/**
 * Lists all available fonts asynchronously (Node.js only)
 * @param callback - Optional callback function (err, fontList) => void
 * @returns Promise<string[]> - Array of font names
 */
function fonts(callback);

/**
 * Lists all available fonts synchronously (Node.js only)
 * @returns string[] - Array of font names
 */
function fontsSync();

Usage Examples:

// Async font listing
const availableFonts = await figlet.fonts();
console.log(`Found ${availableFonts.length} fonts:`, availableFonts);

// Callback-based listing
figlet.fonts((err, fontList) => {
  if (err) {
    console.error("Could not list fonts:", err);
    return;
  }
  
  console.log("Available fonts:");
  fontList.forEach(font => console.log(`  - ${font}`));
});

// Synchronous listing
try {
  const fonts = figlet.fontsSync();
  const randomFont = fonts[Math.floor(Math.random() * fonts.length)];
  console.log(`Using random font: ${randomFont}`);
} catch (err) {
  console.error("Font listing failed:", err);
}

Font Parsing

Parse custom FIGlet font files from raw data.

/**
 * Parses FIGlet font data and stores it for use
 * @param fontName - Name to assign to the parsed font
 * @param data - Raw FIGlet font file content (.flf format)
 * @returns object - Font configuration object
 * @throws Error if font data is invalid or malformed
 */
function parseFont(fontName, data);

Usage Examples:

const fs = require("fs");

// Parse custom font file
try {
  const fontData = fs.readFileSync("./custom-fonts/MyFont.flf", "utf8");
  const fontOptions = figlet.parseFont("MyCustomFont", fontData);
  
  console.log("Custom font parsed successfully");
  console.log("Font height:", fontOptions.height);
  
  // Now use the custom font
  const result = figlet.textSync("Hello", { font: "MyCustomFont" });
  console.log(result);
} catch (err) {
  console.error("Font parsing failed:", err.message);
}

// Parse font from HTTP response
fetch("https://example.com/fonts/CustomFont.flf")
  .then(response => response.text())
  .then(fontData => {
    const options = figlet.parseFont("NetworkFont", fontData);
    return figlet.text("Network Font Test", { font: "NetworkFont" });
  })
  .then(ascii => console.log(ascii))
  .catch(err => console.error("Network font loading failed:", err));

Font Preloading

Preload multiple fonts for efficient synchronous usage.

/**
 * Preloads multiple fonts for later synchronous use
 * @param fonts - Array of font names to preload
 * @param callback - Optional callback function () => void
 * @returns Promise<void> - Resolves when all fonts are loaded
 */
function preloadFonts(fonts, callback);

Usage Examples:

// Preload fonts for application startup
const appFonts = ["Standard", "Big", "Ghost", "Larry 3D", "Doom"];

figlet.preloadFonts(appFonts)
  .then(() => {
    console.log("All fonts preloaded successfully");
    
    // Now use textSync with any preloaded font
    const results = appFonts.map(font => ({
      font,
      art: figlet.textSync("TEST", { font })
    }));
    
    results.forEach(({ font, art }) => {
      console.log(`\n--- ${font} ---`);
      console.log(art);
    });
  })
  .catch(err => console.error("Font preloading failed:", err));

// Callback-based preloading
figlet.preloadFonts(["Standard", "Big"], () => {
  console.log("Fonts ready for synchronous use");
});

Font Configuration Structure

Loaded fonts return configuration objects with the following structure:

interface FontOptions {
  hardBlank: string;        // Hard blank character
  height: number;           // Font height in lines
  baseline: number;         // Baseline position
  maxLength: number;        // Maximum character width
  oldLayout: number;        // Legacy layout value
  numCommentLines: number;  // Number of comment lines in font file
  printDirection: number;   // Default print direction (0=LTR, 1=RTL)
  fullLayout: number;       // Full layout specification
  codeTagCount: number;     // Number of code tags
  fittingRules: {          // Character fitting rules
    hLayout: number;        // Horizontal layout mode
    vLayout: number;        // Vertical layout mode
    hRule1: boolean;        // Horizontal rule 1 (equal character smushing)
    hRule2: boolean;        // Horizontal rule 2 (underscore smushing)
    hRule3: boolean;        // Horizontal rule 3 (hierarchy smushing)
    hRule4: boolean;        // Horizontal rule 4 (opposite pair smushing)
    hRule5: boolean;        // Horizontal rule 5 (big X smushing)
    hRule6: boolean;        // Horizontal rule 6 (hardblank smushing)
    vRule1: boolean;        // Vertical rule 1 (equal character smushing)
    vRule2: boolean;        // Vertical rule 2 (underscore smushing)
    vRule3: boolean;        // Vertical rule 3 (hierarchy smushing)
    vRule4: boolean;        // Vertical rule 4 (horizontal line smushing)
    vRule5: boolean;        // Vertical rule 5 (vertical line supersmushing)
  };
}

Platform Differences

Node.js Environment

  • Uses fs.readFile() and fs.readFileSync() for font loading
  • Supports fonts() and fontsSync() for font discovery
  • Can load fonts from local filesystem paths
  • Supports loadFontSync() for synchronous loading

Browser Environment

  • Uses fetch() API for font loading from network
  • loadFontSync() throws error (not implemented)
  • fonts() and fontsSync() not available
  • Requires fetch polyfill for older browsers
  • Font paths relative to figDefaults.fontPath (default: "./fonts")

Error Handling

Font management functions may throw or reject with:

  • File System Errors (Node.js): Permission denied, file not found, invalid path
  • Network Errors (Browser): Failed fetch, CORS issues, invalid URL
  • Parsing Errors: Invalid FIGlet file format, malformed font data
  • Validation Errors: Missing required font characters, invalid header values
// Handle font loading errors
try {
  await figlet.loadFont("NonExistentFont");
} catch (err) {
  if (err.message.includes("Network response was not ok")) {
    console.error("Font file not found on server");
  } else if (err.message.includes("FIGlet header contains invalid values")) {
    console.error("Corrupted font file");
  } else {
    console.error("Unexpected font loading error:", err);
  }
}

docs

configuration.md

font-management.md

index.md

text-generation.md

tile.json