3 Helpful NPM CLI Commands

3 Helpful NPM CLI Commands

NPM is the world's largest software repository. It is the package manager for the node.js platform. NPM has a powerful CLI that developers use to adapt packages to code, download standalone tools, run packages without downloading them using npx, and many more. In this article, we introduce three npm cli commands that will developers to better and easier manage their package.json.

npm ls

This command will print all versions of installed dependencies in a tree structure. If --all specified, it also prints dependencies of dependencies. list will act as an alias for ls.

npm ls <package-spec>

npm pkg

npm pkg automates the management of packages.json files. npm pkg has 3 different sub-commands that help modify or retrieve given object keys in your package.json files. Returned values are always in JSON format.

npm pkg get <field>

Retrieves a key in our package.json file. For example, to see a list of dependencies in your project, you can run:

npm pkg get dependencies

It is possible to get multiple values in one command:

npm pkg get name version author

For getting child values, separate them with a period. For example, if you want to retrieve the name of the author of a project, run the following command:

npm pkg get author.name

npm pkg set <field>=<value>

Defines new properties or overrides existing ones in package.json, using the same syntax for retrieving values from them.

npm pkg set name='Jon Doe'

npm pkg delete <key>

Deletes a key from package.json file. It uses the same syntax for retrieving values. For example, if you want to delete lint from scripts, run:

npm pkg delete scripts.lint

npm audit

The audit command finds any vulnerabilities in your packages by sending a description of project dependencies to your default registry. If any vulnerabilities are found, then the impact and appropriate remediation will be calculated. To fix vulnerabilities, run:

npm audit fix

Note that some vulnerabilities need manual intervention or review to fix.