
Security News
minimatch Patches 3 High-Severity ReDoS Vulnerabilities
minimatch patched three high-severity ReDoS vulnerabilities that can stall the Node.js event loop, and Socket has released free certified patches.
@npmcli/package-json
Advanced tools
Programmatic API to update package.json files. Updates and saves files the
same way the npm cli handles them.
npm install @npmcli/package-json
const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load(path)
// $ cat package.json
// {
// "name": "foo",
// "version": "1.0.0",
// "dependencies": {
// "a": "^1.0.0",
// "abbrev": "^1.1.1"
// }
// }
pkgJson.update({
dependencies: {
a: '^1.0.0',
b: '^1.2.3',
},
workspaces: [
'./new-workspace',
],
})
await pkgJson.save()
// $ cat package.json
// {
// "name": "foo",
// "version": "1.0.0",
// "dependencies": {
// "a": "^1.0.0",
// "b": "^1.2.3"
// },
// "workspaces": [
// "./new-workspace"
// ]
// }
There is also a helper function exported for opening a package.json file with no extra normalization or saving functionality.
const { readPackage } = require('@npmcli/package-json/lib/read-package')
const rawData = await readPackage('./package.json')
// rawData will now have the package.json contents with no changes or normalizations
constructor()Creates a new empty instance of PackageJson.
async PackageJson.create(path)Creates an empty package.json at the given path. If one already exists
it will be overwritten.
async PackageJson.load(path, opts = {})Loads a package.json at the given path.
opts: Object can contain:
create: Boolean if true, a new package.json will be created if one does not already exist. Will not clobber ane existing package.json that can not be parsed.Loads contents of a package.json file located at ./:
const PackageJson = require('@npmcli/package-json')
const pkgJson = new PackageJson()
await pkgJson.load('./')
Throws an error in case a package.json file is missing or has invalid contents.
async PackageJson.load(path)Convenience static method that returns a new instance and loads the contents of a package.json file from that location.
path: String that points to the folder from where to read the package.json fromLoads contents of a package.json file located at ./:
const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
async PackageJson.normalize()Intended for normalizing package.json files in a node_modules tree. Some light normalization is done to ensure that it is ready for use in @npmcli/arborist
path: String that points to the folder from where to read the package.json fromopts: Object can contain:
strict: Boolean enables optional strict mode when applying the normalizeData stepsteps: Array optional normalization steps that will be applied to the package.json file, replacing the default stepsroot: Path optional git root to provide when applying the gitHead stepchanges: Array if provided, a message about each change that was made to the packument will be added to this arrayasync PackageJson.normalize(path, opts = {})Convenience static that calls load before calling normalize
path: String that points to the folder from where to read the package.json fromopts: Object can contain:
strict: Boolean enables optional strict mode when applying the normalizeData stepsteps: Array optional normalization steps that will be applied to the package.json file, replacing the default stepsroot: Path optional git root to provide when applying the gitHead stepchanges: Array if provided, a message about each change that was made to the packument will be added to this arrayasync PackageJson.prepare()Like normalize but intended for preparing package.json files for publish.
PackageJson.syncNormalize()This calls normalize synchronously. Most consumers of this package should avoid using this. It was added because some parts of npm were normalizing package content in class constructors and needed this affordance. It will silently ignore any asynchronous steps asked for. Again, this is a compatiblity affordance for some code in npm that is currently impossible to change without a significant semver major change, and is best not used.
async PackageJson.prepare(path, opts = {})Convenience static that calls load before calling prepare
path: String that points to the folder from where to read the package.json fromopts: Object can contain:
strict: Boolean enables optional strict mode when applying the normalizeData stepsteps: Array optional normalization steps that will be applied to the package.json file, replacing the default stepsroot: Path optional git root to provide when applying the gitHead stepchanges: Array if provided, a message about each change that was made to the packument will be added to this arrayasync PackageJson.fix()Like normalize but intended for the npm pkg fix command.
PackageJson.update(content)Updates the contents of a package.json with the content provided.
content: Object containing the properties to be updated/replaced in the
package.json file.Special properties like dependencies, devDependencies,
optionalDependencies, peerDependencies will have special logic to handle
the update of these options, such as sorting and deduplication.
Adds a new script named new-script to your package.json scripts property:
const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.update({
scripts: {
...pkgJson.content.scripts,
'new-script': 'echo "Bom dia!"'
}
})
NOTE: When working with dependencies, it's important to provide values for all known dependency types as the update logic has some interdependence in between these properties.
A safe way to add a devDependency AND remove all peer dependencies of an
existing package.json:
const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.update({
dependencies: pkgJson.content.dependencies,
devDependencies: {
...pkgJson.content.devDependencies,
foo: '^foo@1.0.0',
},
peerDependencies: {},
optionalDependencies: pkgJson.content.optionalDependencies,
})
PackageJson.contentGetter that retrieves the normalized Object read from the loaded
package.json file.
const PackageJson = require('@npmcli/package-json')
const pkgJson = await PackageJson.load('./')
pkgJson.content
// -> {
// name: 'foo',
// version: '1.0.0'
// }
async PackageJson.save([options])Saves the current content to the same location used when calling load().
options: Object (optional)
sort: Boolean (optional) — If true, sorts the keys in the resulting package.json file for consistency and readability.[!NOTE] The sort order for
package.jsonis based on the conventions from sort-package-json, cross-checked with the official npm types and documentation:
edit-json-file is a simple Node.js library for editing JSON files. It provides basic functionalities for reading, updating, and saving JSON files. Compared to @npmcli/package-json, it is more generic and not specifically tailored for package.json files.
jsonfile is a Node.js library for easily reading and writing JSON files. It offers a straightforward API for working with JSON files but lacks the specialized features for handling package.json files that @npmcli/package-json provides.
write-json-file is a Node.js library focused on writing JSON files. It provides a simple API for writing JSON data to a file. While it is useful for general JSON file operations, it does not offer the package.json-specific utilities found in @npmcli/package-json.
FAQs
Programmatic API to update package.json
The npm package @npmcli/package-json receives a total of 9,691,752 weekly downloads. As such, @npmcli/package-json popularity was classified as popular.
We found that @npmcli/package-json demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 6 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
minimatch patched three high-severity ReDoS vulnerabilities that can stall the Node.js event loop, and Socket has released free certified patches.

Research
/Security News
Socket uncovered 26 malicious npm packages tied to North Korea's Contagious Interview campaign, retrieving a live 9-module infostealer and RAT from the adversary's C2.

Research
An impersonated golang.org/x/crypto clone exfiltrates passwords, executes a remote shell stager, and delivers a Rekoobe backdoor on Linux.