CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-license-checker

Check license info for a package and its dependencies

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

file-operations.mddocs/

File Operations

License file extraction and JSON parsing utilities for advanced license management workflows.

Capabilities

License File Extraction

Extracts individual license files from scanned packages to a specified output directory for compliance archiving and legal review.

/**
 * Extract license files from packages to output directory
 * @param data - License data from init() callback
 * @param outDir - Output directory path for extracted files
 */
function asFiles(data: LicenseData, outDir: string): void;

Usage Example:

const checker = require("license-checker");
const path = require("path");

checker.init({ start: process.cwd() }, function(err, packages) {
  if (err) throw err;
  
  // Extract all license files to ./licenses directory
  checker.asFiles(packages, "./licenses");
  
  console.log("License files extracted to ./licenses");
});

Behavior:

  • Creates the output directory if it doesn't exist (including parent directories)
  • Copies license files with names formatted as: {package-name}@{version}-LICENSE.txt
  • Only processes packages that have a licenseFile path and the file exists
  • Warns to console for packages without accessible license files
  • Preserves original file content and encoding

Example Output Structure:

licenses/
├── chalk@2.4.2-LICENSE.txt
├── debug@3.2.7-LICENSE.txt
├── nopt@4.0.3-LICENSE.txt
├── mkdirp@0.5.5-LICENSE.txt
└── semver@5.7.1-LICENSE.txt

File Naming:

  • Package names with scopes: @angular/core@12.0.0@angular/core@12.0.0-LICENSE.txt
  • Special characters preserved in filenames
  • Consistent -LICENSE.txt suffix for all extracted files

Error Handling:

  • Missing source files: Logs warning and continues processing other packages
  • Permission errors: Logs warning for inaccessible files
  • Directory creation failures: Throws error if output directory cannot be created
  • Invalid paths: Handles and reports path resolution issues

JSON File Parsing

Utility function for parsing JSON files with error handling, commonly used for custom format specifications.

/**
 * Parse JSON file from filesystem path
 * @param jsonPath - Absolute or relative path to JSON file
 * @returns Parsed JSON object or Error instance on failure
 */
function parseJson(jsonPath: string): object | Error;

Usage Examples:

const checker = require("license-checker");

// Parse custom format file
const customFormat = checker.parseJson("./custom-format.json");

if (customFormat instanceof Error) {
  console.error("Failed to parse custom format:", customFormat.message);
} else {
  // Use parsed format with init
  checker.init({
    start: process.cwd(),
    customFormat: customFormat
  }, callback);
}

// Alternative usage with path validation
const formatPath = "./custom-format.json";
if (typeof formatPath === "string") {
  const format = checker.parseJson(formatPath);
  if (!(format instanceof Error)) {
    console.log("Loaded custom format:", format);
  }
}

Return Values:

  • Success: Returns parsed JavaScript object
  • File not found: Returns Error with descriptive message
  • Invalid JSON: Returns Error with parsing details
  • Permission denied: Returns Error with access details
  • Invalid path: Returns Error for non-string paths

Error Types:

// File system errors
const result = checker.parseJson("./nonexistent.json");
// Returns: Error("ENOENT: no such file or directory...")

// JSON parsing errors  
const result = checker.parseJson("./invalid.json");
// Returns: Error("Unexpected token } in JSON at position 15")

// Type validation
const result = checker.parseJson(123);
// Returns: Error("did not specify a path")

Custom Format File Example:

{
  "name": "",
  "version": "",
  "licenses": "",
  "repository": "",
  "publisher": "",
  "description": "No description available",
  "licenseText": false,
  "copyright": false
}

CLI Integration

Both file operations integrate with the CLI tool:

# Extract license files to directory
license-checker --files ./extracted-licenses

# Use custom format from JSON file
license-checker --customPath ./my-format.json --csv

# Combine file extraction with other outputs
license-checker --files ./licenses --json --out report.json

CLI File Extraction:

  • The --files flag specifies output directory for license file extraction
  • Works in combination with other output formats
  • Creates directory structure automatically
  • Provides progress feedback for large dependency trees

CLI Custom Format:

  • The --customPath flag loads JSON format specification
  • Validates file existence and JSON syntax before scanning
  • Applies custom format to CSV, Markdown, and JSON outputs
  • Reports parsing errors with helpful messages

Integration Patterns

Compliance Archiving:

const checker = require("license-checker");
const fs = require("fs");
const path = require("path");

function createComplianceReport(projectPath, outputDir) {
  checker.init({ 
    start: projectPath,
    production: true  // Only production dependencies for deployment
  }, function(err, packages) {
    if (err) throw err;
    
    // Extract license files
    checker.asFiles(packages, path.join(outputDir, "licenses"));
    
    // Create summary report
    const summary = checker.asSummary(packages);
    fs.writeFileSync(path.join(outputDir, "license-summary.txt"), summary);
    
    // Create detailed CSV
    const csv = checker.asCSV(packages);
    fs.writeFileSync(path.join(outputDir, "license-details.csv"), csv);
    
    console.log(`Compliance report created in ${outputDir}`);
  });
}

Custom Analysis:

// Load analysis configuration
const analysisConfig = checker.parseJson("./analysis-config.json");

if (analysisConfig instanceof Error) {
  console.error("Configuration error:", analysisConfig.message);
  process.exit(1);
}

checker.init({
  start: process.cwd(),
  customFormat: analysisConfig.format,
  exclude: analysisConfig.excludeLicenses,
  production: analysisConfig.productionOnly
}, function(err, packages) {
  // Process results with custom configuration
  const report = checker.asMarkDown(packages, analysisConfig.format);
  fs.writeFileSync("analysis-report.md", report);
});

docs

file-operations.md

formatting.md

index.md

scanning.md

tile.json