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

configuration.mddocs/

Configuration

Configuration management, default settings, and font metadata access for advanced usage scenarios and application customization.

Capabilities

Default Configuration

Manage global default settings that apply to all figlet operations.

/**
 * Get or set default configuration options
 * @param options - Optional configuration object to merge with defaults
 * @returns object - Current default configuration (deep copy)
 */
function defaults(options);

Usage Examples:

const figlet = require("figlet");

// Get current defaults
const currentDefaults = figlet.defaults();
console.log("Current font:", currentDefaults.font);
console.log("Font path:", currentDefaults.fontPath);

// Set new defaults
figlet.defaults({
  font: "Ghost",
  fontPath: "./custom-fonts"
});

// All subsequent calls will use new defaults
const result1 = figlet.textSync("Hello");  // Uses Ghost font
const result2 = figlet.textSync("World", { font: "Big" });  // Overrides to Big

// Reset to specific defaults
figlet.defaults({
  font: "Standard",
  fontPath: "./fonts"
});

Font Metadata

Access detailed metadata about loaded fonts including layout rules and character information.

/**
 * Retrieve metadata about a specific font
 * @param fontName - Name of the font to query
 * @param callback - Optional callback function (err, options, headerComment) => void
 * @returns Promise<[object, string]> - Array containing font options and header comment
 */
function metadata(fontName, callback);

Usage Examples:

// Promise-based metadata access
const [fontOptions, headerComment] = await figlet.metadata("Standard");
console.log("Font height:", fontOptions.height);
console.log("Baseline:", fontOptions.baseline);
console.log("Header comment:", headerComment);
console.log("Fitting rules:", fontOptions.fittingRules);

// Callback-based metadata access
figlet.metadata("Big", (err, options, comment) => {
  if (err) {
    console.error("Could not get metadata:", err);
    return;
  }
  
  console.log(`Font: Big`);
  console.log(`Height: ${options.height} lines`);
  console.log(`Max character width: ${options.maxLength}`);
  console.log(`Print direction: ${options.printDirection === 0 ? 'LTR' : 'RTL'}`);
  console.log(`Comment: ${comment}`);
});

// Analyze font capabilities
async function analyzeFontCapabilities(fontName) {
  try {
    const [options] = await figlet.metadata(fontName);
    const rules = options.fittingRules;
    
    console.log(`\nFont Analysis: ${fontName}`);
    console.log(`Dimensions: ${options.maxLength}x${options.height}`);
    console.log(`Horizontal Layout: ${getLayoutName(rules.hLayout)}`);
    console.log(`Vertical Layout: ${getLayoutName(rules.vLayout)}`);
    console.log(`Smushing Rules: H${countSmushingRules(rules, 'h')} V${countSmushingRules(rules, 'v')}`);
  } catch (err) {
    console.error(`Analysis failed for ${fontName}:`, err.message);
  }
}

function getLayoutName(layout) {
  const layouts = ["Full Width", "Fitting", "Smushing", "Controlled Smushing"];
  return layouts[layout] || "Unknown";
}

function countSmushingRules(rules, prefix) {
  return Object.keys(rules)
    .filter(key => key.startsWith(prefix + 'Rule') && rules[key])
    .length;
}

Advanced Font Data Access

Access the internal font storage and character data for advanced use cases.

/**
 * Internal font storage object containing all loaded fonts
 * @type object
 * @readonly
 */
figlet.figFonts;

Usage Examples:

// Examine loaded fonts
console.log("Currently loaded fonts:", Object.keys(figlet.figFonts));

// Access font character data (advanced usage)
const standardFont = figlet.figFonts["Standard"];
if (standardFont) {
  console.log("Font options:", standardFont.options);
  console.log("Font comment:", standardFont.comment);
  console.log("Number of characters:", standardFont.numChars);
  
  // Access character ASCII art (character code 65 = 'A')
  const charA = standardFont[65];
  if (charA) {
    console.log("Character 'A' representation:");
    charA.forEach(line => console.log(line));
  }
}

// Check if font is already loaded
function isFontLoaded(fontName) {
  return fontName in figlet.figFonts;
}

// Get font loading status
function getFontStatus() {
  const loaded = Object.keys(figlet.figFonts);
  return {
    totalLoaded: loaded.length,
    fonts: loaded,
    hasStandard: loaded.includes("Standard")
  };
}

Configuration Options Reference

Default Configuration Object

interface FigletDefaults {
  font: string;       // Default font name ("Standard")
  fontPath: string;   // Path to font directory ("./fonts")
}

The default configuration contains:

  • font (string): Default font name used when no font is specified (default: "Standard")
  • fontPath (string): Base path for font file loading (default: "./fonts" in browsers, computed dynamically in Node.js)

Layout Configuration Constants

Internal constants used for layout control:

// Layout mode constants (internal use)
const FULL_WIDTH = 0;           // Full width spacing
const FITTING = 1;              // Characters touch but don't overlap  
const SMUSHING = 2;             // Universal character overlapping
const CONTROLLED_SMUSHING = 3;  // Rule-based character overlapping

Font File Structure

FIGlet font files (.flf) contain structured character data:

// Font file header structure
interface FigletHeader {
  signature: string;        // "flf2a" signature
  hardBlank: string;        // Hard blank character  
  height: number;           // Character height in lines
  baseline: number;         // Baseline position
  maxLength: number;        // Maximum character width
  oldLayout: number;        // Legacy layout specification
  commentLines: number;     // Number of header comment lines
  printDirection?: number;  // Print direction (optional)
  fullLayout?: number;      // Full layout specification (optional)
  codeTagCount?: number;    // Code tag count (optional)
}

Environment-Specific Configuration

Node.js Configuration

// Node.js specific font path resolution
const path = require("path");
const fontDir = path.join(__dirname, "../fonts/");

// Font loading uses filesystem
figlet.loadFontSync = function(name) {
  const fs = require("fs");
  const fontPath = path.join(fontDir, name + ".flf");
  const fontData = fs.readFileSync(fontPath, { encoding: "utf-8" });
  return figlet.parseFont(name, fontData);
};

Browser Configuration

// Browser uses fetch API for font loading
figlet.defaults({
  fontPath: "./fonts"  // Relative to current page
});

// Font loading uses network requests
figlet.loadFont = function(name) {
  return fetch(`${figDefaults.fontPath}/${name}.flf`)
    .then(response => response.text())
    .then(data => figlet.parseFont(name, data));
};

Error Handling

Configuration functions may encounter:

  • Invalid Options: When configuration parameters are malformed
  • Font Loading Errors: When default font cannot be loaded
  • Path Resolution Errors: When font paths are invalid or inaccessible
// Safe configuration updates
try {
  figlet.defaults({
    font: "CustomFont",
    fontPath: "./assets/fonts"
  });
  
  // Test the configuration
  const result = figlet.textSync("Test");
  console.log("Configuration successful");
} catch (err) {
  console.error("Configuration failed:", err.message);
  
  // Restore safe defaults
  figlet.defaults({
    font: "Standard",
    fontPath: "./fonts"
  });
}

// Validate font metadata
figlet.metadata("UnknownFont")
  .then(([options, comment]) => {
    console.log("Font is valid and loaded");
  })
  .catch(err => {
    console.error("Font metadata unavailable:", err.message);
  });

Advanced Usage Patterns

Dynamic Font Management

// Create font manager utility
class FontManager {
  constructor() {
    this.loadedFonts = new Set();
    this.fontCache = new Map();
  }
  
  async ensureFont(fontName) {
    if (!this.loadedFonts.has(fontName)) {
      const options = await figlet.loadFont(fontName);
      this.loadedFonts.add(fontName);
      this.fontCache.set(fontName, options);
      return options;
    }
    return this.fontCache.get(fontName);
  }
  
  async generateWithFont(text, fontName, options = {}) {
    await this.ensureFont(fontName);
    return figlet.text(text, { ...options, font: fontName });
  }
}

// Usage
const fontManager = new FontManager();
const result = await fontManager.generateWithFont("Hello", "Ghost");

Configuration Profiles

// Create configuration profiles for different use cases
const profiles = {
  compact: {
    horizontalLayout: "fitted",
    verticalLayout: "fitted",
    width: 60
  },
  
  banner: {
    font: "Big",
    horizontalLayout: "controlled smushing",
    width: 120
  },
  
  artistic: {
    font: "Larry 3D",
    horizontalLayout: "universal smushing",
    verticalLayout: "universal smushing"
  }
};

// Apply profile
function useProfile(profileName) {
  const profile = profiles[profileName];
  if (profile) {
    figlet.defaults(profile);
    console.log(`Applied ${profileName} profile`);
  }
}

docs

configuration.md

font-management.md

index.md

text-generation.md

tile.json