📦 packageJson
A set of functions to programmatically create and manage package.json files for Node.js projects, including batch creation in subdirectories and automated publishing.
Import
1import { JPM } from "hbh-nodes";2const { createPackageJson, createPackagesInSubdirs, publishAllPackages } = JPM;
createPackageJson(dirPath, newJson)
Creates a package.json file in the specified directory. If the file already exists, it will not overwrite it.
Parameters:
dirPath(string) – Path to the directory wherepackage.jsonshould be created.newJson(object, optional) – Overrides or additional fields for thepackage.json.
Returns:
- JSON string of the final package content.
Example:
1createPackageJson("./my-lib", {2 name: "my-lib",3 version: "1.0.0",4 author: "HBH"5});
Edge Cases:
- If a
package.jsonalready exists, it is not overwritten. - Default fields are merged with any custom fields provided.
createPackagesInSubdirs(parentDir, defaultJsonOverrides)
Creates package.json files in all subdirectories of a given directory.
Parameters:
parentDir(string) – Directory containing multiple package folders.defaultJsonOverrides(object, optional) – Fields to override default values for all packages.
Example:
1createPackagesInSubdirs("./packages", {2 license: "MIT",3 author: "HBH"4});
Edge Cases:
- Uses the folder name as the package
nameby default. - Only directories are processed; files are ignored.
- Existing
package.jsonfiles are preserved.
publishAllPackages(parentDir)
Publishes all Node.js packages in subdirectories under a specified directory using npm publish.
Parameters:
parentDir(string) – Directory containing multiple package folders with validpackage.json.
Example:
1publishAllPackages("./packages");
Behavior:
- Runs
npm publish --access publicin each subdirectory. - Logs success or failure for each package.
Edge Cases:
- Subdirectories without
package.jsonare skipped. - Errors in publishing one package do not stop publishing of others.
- Output of
npm publishis displayed in the console.