license-checker

repository·master·Indexed 23 days ago

https://github.com/davglass/license-checker

A utility for scanning node_modules to report the licenses of all installed dependencies. Version 25.0.1 supports various output formats including Tree, JSON, CSV, Markdown, and Summary. It can be used as a CLI tool to enforce license compliance via --failOn and --onlyAllow flags, or as a Node.js module using the checker.init() function to programmatically retrieve package data.

Tokens
2.8K
Snippets
4
Records
13
Agent score
81%

What's inside license-checker

  1. Use custom formats for JSON and CSV output

    master

    You can define a custom output structure using the --customPath flag and a JSON configuration file.

    • For CSV: Specifies the columns to include. The module_name column is always included as the first column.
    • For JSON: Adds the specified items to the standard output.

    Available items for custom formats:

    • name, version, description, repository, publisher, email, url, licenses, licenseFile, licenseText, licenseModified.

    You can also provide default values for these items in your custom format JSON file.

    license-checker --customPath customFormatExample.json
  2. Install and run license-checker via CLI

    master

    To use license-checker to inspect the licenses of a project and its dependencies, install it globally via npm and run the command within your project directory.

    # Install globally
    npm install -g license-checker
    
    # Run in your project folder
    license-checker

    Output displays a tree of dependencies, their repositories, and their licenses. An asterisk (*) next to a license name indicates the license was deduced from files like README or LICENSE rather than being explicitly stated in package.json.

  3. Enforce license compliance with --failOn and --onlyAllow

    master

    You can use the CLI to automatically fail a build (exit with code 1) if certain license conditions are met.

    • --failOn [list]: Fails if any license in the semicolon-separated list is found.
    • --onlyAllow [list]: Fails if any license not in the semicolon-separated list is found.

    Constraint: You cannot use --failOn and --onlyAllow at the same time.

  4. How license scanning works

    master

    The license checker follows a specific precedence logic to identify a package's license:

    1. package.json: It first looks at the license or licenses field in the dependency's package.json.
    2. README.md: If no license is found in package.json, it attempts to parse the README.md file.
    3. File System Scan: If neither of the above works, it scans the package directory for files that match common license filenames (e.g., LICENSE, COPYING).

    If a package is marked as private in its package.json, its license is reported as UNLICENSED.

  5. Use the license-checker CLI

    master

    The license-checker CLI tool scans your NPM dependencies to report their licenses. It supports various output formats (Tree, JSON, CSV, Markdown, Summary) and allows for strict license enforcement via exit codes.

    Note on Delimiters: As of v17, when using --failOn or --onlyAllow, use semicolons (;) as delimiters instead of commas, as license names may contain commas.

  6. Debug license-checker output

    master

    The tool uses the debug module for internal logging. You can view debug output by setting the DEBUG environment variable to one of the following markers:

    • license-checker:error: For error logs.
    • license-checker:log: For non-error logs.
    • license-checker*: To see all logs.

    Example:

    $ export DEBUG=license-checker*; license-checker
    $ export DEBUG=license-checker*; license-checker
  7. Use license-checker as a Node.js module

    master

    You can require license-checker in your application to programmatically retrieve package data.

    Use checker.init(options, callback) where options can include a start path. The callback receives an error or the sorted package data as an Object.

    var checker = require('license-checker');
    
    checker.init({
        start: '/path/to/start/looking'
    }, function(err, packages) {
        if (err) {
            //Handle error
        } else {
            //The sorted package data
            //as an Object
        }
    });
  8. CLI Options Reference

    master

    The license-checker CLI provides several flags to filter, format, and validate licenses.

    Note on Delimiters: As of v17.0.0, the --failOn, --onlyAllow, --packages, and --excludePackages arguments use semicolons (;) as delimiters instead of commas to avoid conflicts with license names containing commas.

  9. Format scanned data as a Tree, Summary, CSV, or Markdown

    master

    Once you have the sorted data object from init(), you can use the following methods to format it for different outputs:

    asTree(sorted)

    Returns a string representation of the dependency tree using treeify.

    asSummary(sorted)

    Returns a tree representation of the count of each license type found (e.g., MIT: 5, BSD: 2).

    asCSV(sorted, [customFormat], [csvComponentPrefix])

    Returns a CSV string.

    • If customFormat is provided, it uses those keys as columns.
    • If not, it defaults to module name, license, and repository.
    • csvComponentPrefix (string) can be used to add a custom prefix column.

    asMarkDown(sorted, [customFormat])

    Returns a Markdown string.

    • If customFormat is provided, it creates a nested list of the specified keys.
    • If not, it creates a simple list: [package](repo) - license.

    asFiles(json, outDir)

    Takes the scanned JSON data and extracts the actual license text files into the specified outDir, naming them {moduleName}-LICENSE.txt.

  10. Initialize license scanning with init()

    master

    The init function is the primary entry point for programmatically scanning dependencies for licenses. It performs a recursive scan of the dependency tree starting from a specified path and returns a structured object containing license information for each package.

    Parameters

    • options (Object): Configuration object (see Configuration Options).
    • callback (Function): A callback function called with (err, data). data is an object where keys are package@version and values are module information objects.

    Usage

    const checker = require('license-checker');
    
    checker.init({ start: './' }, (err, data) => {
      if (err) {
        console.error(err);
        return;
      }
      console.log(data);
    });
  11. Configuration options for init()

    master

    When calling init(options, callback), the options object controls how the dependency tree is traversed, filtered, and formatted.

    OptionTypeDescription
    startstringThe starting directory or path to scan.
    productionbooleanIf true, only production dependencies are included.
    developmentbooleanIf true, only development dependencies are included.
    directnumberControls the depth of the dependency scan.
    colorbooleanWhether to enable colorized output in the returned data.
    unknownbooleanIf true, treats licenses containing * as UNKNOWN.
    onlyunknownbooleanIf true, the result will only include packages with UNKNOWN or * licenses.
    excludestringA semicolon-separated list of SPDX license expressions to exclude.
    packagesstringA semicolon-separated list of package names to whitelist.
    excludePackagesstringA semicolon-separated list of package names to blacklist.
    excludePrivatePackagesbooleanIf true, removes private packages from the results.
    onlyAllowstringA semicolon-separated list of licenses that are permitted. If a package doesn't match, the process exits with code 1.
    failOnstringA semicolon-separated list of licenses that are forbidden. If a package matches, the process exits with code 1.
    customFormatObjectAn object defining which properties to include in the output. Setting a property to false excludes it.
    customPathstringPath to a JSON file containing a custom format configuration.
    relativeLicensePathbooleanIf true, uses relative paths for license files.
    excludestringSemicolon-separated list of licenses to exclude (supports SPDX).
  12. Reference: license-checker CLI flags

    master

    The following flags are available for the license-checker command line interface:

    --production only show production dependencies.
       --development only show development dependencies.
       --unknown report guessed licenses as unknown licenses.
       --start [path of the initial json to look for]
       --onlyunknown only list packages with unknown or guessed licenses.
       --json output in json format.
       --csv output in csv format.
       --csvComponentPrefix column prefix for components in csv file
       --out [filepath] write the data to a specific file.
       --customPath to add a custom Format file in JSON
       --exclude [list] exclude modules which licenses are in the comma-separated list from the output
       --relativeLicensePath output the location of the license files as relative paths
       --summary output a summary of the license usage
       --failOn [list] fail (exit with code 1) on the first occurrence of the licenses of the semicolon-separated list
       --onlyAllow [list] fail (exit with code 1) on the first occurrence of the licenses not in the semicolon-seperated list
       --direct look for direct dependencies only
       --packages [list] restrict output to the packages (package@version) in the semicolon-seperated list
       --excludePackages [list] restrict output to the packages (package@version) not in the semicolon-seperated list
       --excludePrivatePackages restrict output to not include any package marked as private
       --version The current version
       --help  The text you are reading right now :)