npm CLI Documentation

repository·latest·Indexed 27 days ago

https://github.com/npm/cli

Documentation for npm version 12.0.1, a JavaScript package manager used to install, manage, and publish packages in the npm registry. Includes details on the npm CLI and the @npmcli/arborist library for inspecting and managing node_modules through the construction of actual, virtual, and ideal dependency trees.

Tokens
86.4K
Snippets
183
Records
615
Agent score
94%

What's inside npm

  1. Use libnpmaccess to manage npm package access and permissions

    latest

    libnpmaccess is a Node.js library that provides programmatic access to the functionality of the npm access CLI command. It allows you to manage account MFA settings, list packages and permissions, view package collaborators, and define permissions for users, organizations, and teams.

    const access = require('libnpmaccess')
    const opts = { '//registry.npmjs.org/:_authToken: 'npm_token }
    
    // List all packages @zkat has access to on the npm registry.
    console.log(Object.keys(await access.getPackages('zkat', opts)))
  2. Understand the npm dependency hierarchy

    latest

    The npm CLI is composed of several layers of dependencies organized in a hierarchy. Each group of packages depends on the groups listed below it in the chain. This hierarchy helps in understanding which packages are core to the CLI and which are lower-level utilities.

    Dependency Chain (Top to Bottom):

    1. npm (The CLI itself)
    2. @npmcli/mock-registry, libnpmdiff, libnpmexec, libnpmfund, libnpmpack
    3. @npmcli/arborist
    4. @npmcli/metavuln-calculator
    5. pacote, @npmcli/config, libnpmversion
    6. @npmcli/map-workspaces, @npmcli/run-script, libnpmaccess, libnpmorg, libnpmpublish, libnpmsearch, libnpmteam, init-package-json, npm-profile
    7. @npmcli/package-json, npm-registry-fetch
    8. @npmcli/git, make-fetch-happen
    9. @npmcli/smoke-tests, @npmcli/installed-package-contents, npm-pick-manifest, cacache, promzard
    10. @npmcli/docs, @npmcli/fs, npm-bundled, @npmcli/promise-spawn, npm-install-checks, npm-package-arg, npm-packlist, bin-links, nopt, parse-conflict-json, @npmcli/mock-globals, read
    11. Low-level utilities including semver, ssri, which, ini, proc-log, and others.
  3. Understand package-lock.json

    latest

    package-lock.json is automatically generated whenever npm modifies the node_modules tree or package.json. It describes the exact dependency tree to ensure that subsequent installs produce identical results across different environments (teammates, CI/CD, deployments).

    Key benefits include:

    • Deterministic Installs: Guarantees identical dependency trees.
    • Time-travel: Allows reverting to previous node_modules states via source control.
    • Visibility: Provides readable diffs for dependency changes.
    • Performance: Optimizes installation by skipping repeated metadata resolutions.
    • Complete Tree Information: Since npm v7, lockfiles contain enough data to reconstruct the tree without reading package.json files constantly.
  4. Understand Node relationships in @npmcli/arborist

    latest

    In @npmcli/arborist, Node objects represent packages and maintain various relationships to reflect how they exist on disk and within the dependency graph. Key relationships include:

    • parent: The package containing the current node's node_modules folder.
    • children: A Map<string, Node> of nodes located within the current node's node_modules folder.
    • fsParent: The node that is the file system parent of the current node (relevant for symlinked packages).
    • fsChildren: A Set<Node> of nodes that are file system children of the current node.
    • target: For Link nodes, the node representing the actual path on disk.
    • linksIn: For target nodes, a Set of all Link nodes pointing to that package.
    • top: A node that has no parent.
  5. Understand Arborist data structures

    latest

    Arborist models a node_modules tree as a logical graph of dependencies overlaid on a physical folder tree. It uses three primary entities:

    • Node: Represents a package folder on disk. It tracks its physical location via node.parent and its contents via node.children (a Map of names to child nodes).
    • Link: Represents a symbolic link to a package. Unlike a Node, dependencies are resolved from the link.target location rather than the link's location.
    • Edge: Represents a dependency relationship between nodes. Each node has edgesIn (nodes that depend on it) and edgesOut (nodes it depends on). Edges have a type ('prod', 'peer', 'dev', or 'optional').
  6. Understand Arborist tree types

    latest

    Arborist manages three distinct representations of the package dependency tree. Understanding which tree you are interacting with is critical for performing operations like diffing or reification:

    1. Actual Tree (arborist.actualTree): Represents the packages currently existing on disk (e.g., in node_modules). It is populated by calling arborist.loadActual().
    2. Virtual Tree (arborist.virtualTree): Represents the package tree as defined in a package-lock.json file. It is populated by calling arborist.loadVirtual().
      • You can specify a specific node as the root: arborist.loadVirtual({ root: nodeObject }).
      • If no root is specified, a package-lock.json must be present, otherwise the load fails.
    3. Ideal Tree (arborist.idealTree): Represents the desired state of the package tree based on package.json, the lockfile, and requested changes. It is populated by calling arborist.buildIdealTree(options).

    Reification Workflow: During the reification process, the idealTree is compared (diffed) against the actualTree. Once arborist.reify() completes, the idealTree is copied to arborist.actualTree because the disk state now matches the intended state.

  7. Understand tree reification in Arborist

    latest

    Tree reification is the process of transforming an existing physical node_modules directory structure (the actualTree) into a new desired state (the idealTree) based on a package manifest. This involves adding new dependencies, updating existing ones, and removing obsolete packages.

    Arborist implements two primary strategies for this process:

    1. Reify-A (Safe Rollback-able Process): Designed to minimize Windows EPERM errors by avoiding renaming or deleting directories that have recent writes. It uses a 'retire and replace' strategy where old nodes are moved to a hashed temporary directory (e.g., .b-<hash>) so they can be restored if the installation fails.
    2. Reify-B (Fast and Dirty Approach): A high-performance strategy that deletes existing packages before unpacking new ones. This is faster and more disk-efficient but does not support a safe rollback if the process is interrupted.
  8. Install npm

    latest

    npm is typically bundled with Node.js. You can install it via official Node.js distributions or by using a direct installation script from npmjs.com.

    Direct Download

    You can install npm directly using the following script:

    curl -qL https://www.npmjs.com/install.sh | sh

    Node Version Managers

    To manage multiple versions of Node.js and npm, it is recommended to use a Node version manager.

  9. Search npm help documentation with npm help

    latest

    You can search for specific terms within the npm markdown documentation using the npm help command. The command searches documentation files for the provided terms and lists results sorted by relevance.

    If the argument provided to npm help matches a known help topic, it displays that topic. If the argument is not a known topic, npm automatically invokes the help-search functionality to find relevant documentation.