JSPM

  • Created
  • Published
  • Downloads 177
  • Score
    100M100P100Q97579F
  • License MIT

Cross-platform printer library for Node.js, Deno, and Bun

Package Exports

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@printers/printers) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    @printers/printers

    JSR NPM License: MIT Build

    Cross-runtime printer library for Deno, Bun, and Node.js.

    Features

    • 🔄 Cross-runtime compatibility - works in Deno, Bun, and Node.js
    • 🖨️ Cross-platform printing - Windows, macOS, and Linux
    • 🦀 Native performance - Rust backend using the printers crate
    • 🏗️ Multi-architecture support - AMD64 and ARM64 binaries
    • 🔒 Safe testing - simulation mode prevents accidental printing
    • 📊 Async job tracking - non-blocking print jobs with status monitoring
    • 🔍 Rich printer metadata - access all printer properties

    Installation

    Deno

    deno add @printers/printers
    Alternative: NPM
    # Not recommended - use JSR for better tree-shaking
    deno add npm:@printers/printers

    Node.js

    npm install @printers/printers
    # or
    yarn add @printers/printers
    # or
    pnpm add @printers/printers
    Alternative: JSR
    npx jsr add @printers/printers

    Bun

    bun add @printers/printers
    Alternative: JSR
    # Requires JSR CLI
    bunx jsr add @printers/printers

    Quick Start

    import { getAllPrinters, Printer } from "@printers/printers";
    
    // List all available printers
    const printers = getAllPrinters();
    console.log("Available printers:", printers.map((p) => p.name));
    
    // Print a file (returns a Promise)
    const printer = printers[0];
    try {
      await printer.printFile("/path/to/document.pdf", {
        copies: "2",
        orientation: "landscape",
      });
      console.log("Print job completed!");
    } catch (error) {
      console.error("Print failed:", error.message);
    }

    API Reference

    Functions

    getAllPrinters(): Printer[]

    Returns an array of all available system printers.

    getAllPrinterNames(): string[]

    Returns an array of printer names.

    getPrinterByName(name: string): Printer | null

    Find a printer by its exact name.

    printerExists(name: string): boolean

    Check if a printer exists on the system.

    getJobStatus(jobId: number): JobStatus | null

    Get the status of a print job by ID.

    cleanupOldJobs(maxAgeSeconds: number): number

    Remove old completed/failed jobs and return the count removed.

    shutdown(): void

    Shutdown the library and cleanup all background threads. Called automatically on process exit.

    Classes

    Printer

    Represents a system printer with metadata and printing capabilities.

    Properties:

    • name: string - Printer display name
    • systemName: string - System-level printer name
    • driverName: string - Printer driver name
    • uri: string - Printer URI (if available)
    • portName: string - Port name (e.g., "USB001", "LPT1:")
    • processor: string - Print processor (e.g., "winprint")
    • dataType: string - Default data type (e.g., "RAW")
    • description: string - Printer description
    • location: string - Physical location description
    • isDefault: boolean - Whether this is the default printer
    • isShared: boolean - Whether the printer is shared on network
    • state: PrinterState - Current printer state ("READY", "OFFLINE", etc.)
    • stateReasons: string[] - Array of state reason strings

    Methods:

    • static fromName(name: string): Printer | null - Create printer instance from name
    • exists(): boolean - Check if printer is available
    • toString(): string - Get string representation with all fields
    • equals(other: Printer): boolean - Compare with another printer by name
    • dispose(): void - Manually release printer resources (automatic cleanup available)
    • printFile(filePath: string, jobProperties?: Record<string, string>): Promise<void> - Print a file

    Interfaces

    JobStatus

    interface JobStatus {
      id: number;
      printer_name: string;
      file_path: string;
      status: "queued" | "printing" | "completed" | "failed";
      error_message?: string;
      age_seconds: number;
    }

    PrinterState

    type PrinterState = "idle" | "processing" | "stopped" | "unknown";

    Note: The actual printer state comes from the native printer system and may include values like "READY", "OFFLINE", "PAUSED", etc.

    Permissions

    Deno

    deno run --allow-ffi --allow-env your-script.ts
    • --allow-ffi - Required for loading the native library
    • --allow-env - Optional, for reading PRINTERS_JS_SIMULATE environment variable

    Node.js / Bun

    No special permissions required.

    Testing & Safety

    Simulation Mode

    Set PRINTERS_JS_SIMULATE=true to enable simulation mode, which prevents actual printing while testing all functionality:

    Unix/Linux/macOS:

    PRINTERS_JS_SIMULATE=true deno run --allow-ffi --allow-env your-script.ts

    Windows Command Prompt:

    set PRINTERS_JS_SIMULATE=true
    deno run --allow-ffi --allow-env your-script.ts

    Windows PowerShell:

    $env:PRINTERS_JS_SIMULATE="true"
    deno run --allow-ffi --allow-env your-script.ts

    Examples

    Basic Printing

    import { getAllPrinters } from "@printers/printers";
    
    const printers = getAllPrinters();
    if (printers.length > 0) {
      const printer = printers[0];
    
      // Access printer information
      console.log(`Using printer: ${printer.name}`);
      console.log(`Driver: ${printer.driverName}`);
      console.log(`State: ${printer.state}`);
      console.log(`Default: ${printer.isDefault}`);
    
      try {
        await printer.printFile("document.pdf");
        console.log("Print successful");
      } catch (error) {
        console.log("Print failed:", error.message);
      }
    }

    Printer Information & Management

    import {
      cleanupOldJobs,
      getAllPrinterNames,
      getAllPrinters,
      getPrinterByName,
      printerExists,
    } from "@printers/printers";
    
    // List all printers with detailed information
    const printers = getAllPrinters();
    for (const printer of printers) {
      console.log(`\n${printer.name}:`);
      console.log(`  Driver: ${printer.driverName}`);
      console.log(`  State: ${printer.state}`);
      console.log(`  Port: ${printer.portName}`);
      console.log(`  Default: ${printer.isDefault ? "Yes" : "No"}`);
      console.log(`  Shared: ${printer.isShared ? "Yes" : "No"}`);
    
      if (printer.location) {
        console.log(`  Location: ${printer.location}`);
      }
    
      if (printer.stateReasons.length > 0 && printer.stateReasons[0] !== "none") {
        console.log(`  Issues: ${printer.stateReasons.join(", ")}`);
      }
    }
    
    // Check if specific printer exists
    if (printerExists("My Printer")) {
      const printer = getPrinterByName("My Printer");
      console.log("Found printer:", printer?.name);
    }
    
    // Clean up old print jobs (older than 1 hour)
    const cleaned = cleanupOldJobs(3600);
    console.log(`Cleaned up ${cleaned} old print jobs`);

    Working with Printer Properties

    import { getAllPrinters } from "@printers/printers";
    
    const printers = getAllPrinters();
    
    // Find default printer
    const defaultPrinter = printers.find((p) => p.isDefault);
    console.log(`Default printer: ${defaultPrinter?.name || "None"}`);
    
    // Find printers by state
    const readyPrinters = printers.filter((p) => p.state === "READY");
    console.log(`Ready printers: ${readyPrinters.map((p) => p.name).join(", ")}`);
    
    // Find network printers
    const networkPrinters = printers.filter((p) => p.isShared);
    console.log(
      `Network printers: ${networkPrinters.map((p) => p.name).join(", ")}`,
    );

    Platform Support

    OS Architecture Deno (FFI) Bun (FFI) Node.js (N-API)
    Windows x64
    Windows ARM64
    macOS x64
    macOS ARM64
    Linux x64
    Linux ARM64

    Development & Contributing

    For technical information about architecture, build systems, development workflow, and contribution guidelines, see CONTRIBUTING.md.

    License

    MIT License - see LICENSE file for details.