init-package-json

8.2.5 · active · verified Sun Apr 19

init-package-json is a Node.js module designed to programmatically and interactively create or update `package.json` files, primarily used by the npm CLI itself. It provides a wizard-like experience for users, prompting for essential package metadata such as name, version, description, entry point, test command, git repository, keywords, author, and license. The current stable version is 8.2.5, with frequent maintenance releases addressing bug fixes and dependency updates, often tied to releases of other `@npmcli` packages. Its key differentiator is its integration with `promzard` for flexible, scriptable prompting and the ability to utilize custom initialization files, offering a powerful way to standardize `package.json` creation across projects or teams. It is a low-level utility most often consumed by package managers rather than directly by end-user applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically use `init-package-json` to create a `package.json` file in a specified directory, utilizing a custom `promzard` init file to pre-fill common fields and interact with passed configuration data.

const init = require('init-package-json');
const path = require('path');
const fs = require('fs/promises');

async function initializePackage() {
  // Define a temporary custom init file for demonstration purposes
  const tempInitFileContent = `
    module.exports = function (data, cb) {
      data.name = this.basename;
      data.version = '1.0.0';
      data.description = 'A new package initialized via init-package-json!';
      data.main = 'index.js';
      data.scripts = { test: 'echo \"Error: no test specified\" && exit 1' };
      data.license = 'ISC';
      data.author = this.config.author || '';
      cb(null, data);
    };
  `;
  const customInitFilePath = path.join(__dirname, '.npm-init-custom.js');
  await fs.writeFile(customInitFilePath, tempInitFileContent);

  const targetDir = path.join(__dirname, 'my-new-package');
  await fs.mkdir(targetDir, { recursive: true });

  const configData = { author: 'My Name <me@example.com>' };

  try {
    console.log(`Initializing package.json in ${targetDir}...`);
    const resultData = await init(targetDir, customInitFilePath, configData);
    console.log('package.json initialized successfully:');
    console.log(JSON.stringify(resultData, null, 2));
  } catch (error) {
    console.error('Failed to initialize package.json:', error);
  } finally {
    // Clean up the temporary init file
    await fs.unlink(customInitFilePath);
    console.log('Cleaned up temporary init file.');
  }
}

initializePackage();

view raw JSON →