libnpmpack Programmatic Packing API

9.1.5 · active · verified Wed Apr 22

libnpmpack provides the programmatic interface for creating tarballs of npm packages, mirroring the functionality of the `npm pack` command-line tool. As an internal library of the npm CLI, it offers a robust and consistent way to prepare packages for distribution, including handling `.npmignore`, `.gitignore`, and package lifecycle scripts during the packing process. The current stable version of the `libnpmpack` package itself is 9.1.5, though it is often consumed as part of the broader npm CLI, which follows its own release schedule (e.g., v10.x and v11.x branches) and sees frequent updates. Its release cadence is tightly coupled with the npm CLI's monorepo development. A key differentiator is that it's the authoritative, low-level implementation for `npm pack`, ensuring compatibility with npm's official packing logic, unlike third-party alternatives which might deviate in edge cases. It focuses on encapsulating the complex logic of package bundling and file inclusion rules.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `libnpmpack` to programmatically create an npm package tarball from a local directory, including `package.json` and custom files, and then clean up. It simulates a package project and uses the `pack` function with basic options.

import { pack } from 'libnpmpack';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { promises as fs } from 'fs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const projectRoot = join(__dirname, 'my-test-package');
const outputPath = join(__dirname, 'output');

async function createAndPackPackage() {
  await fs.mkdir(projectRoot, { recursive: true });
  await fs.mkdir(outputPath, { recursive: true });

  await fs.writeFile(
    join(projectRoot, 'package.json'),
    JSON.stringify({
      name: 'my-packed-package',
      version: '1.0.0',
      main: 'index.js',
      files: ['index.js', 'data/'],
      scripts: {
        test: 'echo "Error: no test specified" && exit 1'
      }
    }, null, 2)
  );
  await fs.writeFile(join(projectRoot, 'index.js'), 'console.log("Hello from packed package!");');
  await fs.mkdir(join(projectRoot, 'data'), { recursive: true });
  await fs.writeFile(join(projectRoot, 'data', 'config.txt'), 'some config data');
  await fs.writeFile(join(projectRoot, '.npmignore'), 'node_modules\n.git');

  console.log(`Created test package at: ${projectRoot}`);

  try {
    const tarballs = await pack(projectRoot, {
      // Optional: Specify a target directory for the tarball
      // Default is current working directory
      packDestination: outputPath,
      // log: console // You can pass a logger object if needed
    });
    console.log(`Successfully packed package(s) to:`);
    tarballs.forEach(tarballPath => console.log(`- ${tarballPath}`));
  } catch (error) {
    console.error('Failed to pack package:', error);
    process.exit(1);
  } finally {
    // Clean up created files/directories
    await fs.rm(projectRoot, { recursive: true, force: true });
    await fs.rm(outputPath, { recursive: true, force: true });
    console.log('Cleaned up test directories.');
  }
}

createAndPackPackage();

view raw JSON →