When using npm to retrieve the current package version, there are several ways to achieve this. Here, I will introduce two primary methods, providing specific commands and examples.
Method One: Inspect the package.json File
Every project managed by npm has a package.json file that contains project dependency information and the current project's version number. To view the current package version, you can directly inspect this file:
- Open the root directory of the project.
- Open the package.json file.
- Locate the "version" field; its value is the current package version.
Example: Assume your package.json file content is as follows:
json{ "name": "example-project", "version": "1.0.2", "dependencies": { "express": "^4.17.1" } }
In this example, the current package version is 1.0.2.
Method Two: Use the npm list Command
If you want to retrieve the version number directly via the command line, you can use the npm list command. This command lists all npm packages installed in the current project along with their version numbers. To view only the current project's version, you can use the following command:
bashnpm list --depth=0
This command lists the top-level dependencies, i.e., the packages directly installed in the project, without showing deeper dependencies.
Example: In the command line, enter:
bashnpm list --depth=0
You may see output similar to the following:
shellexample-project@1.0.2 /path/to/your/project ├── express@4.17.1
Here, example-project@1.0.2 indicates that the current project's version is 1.0.2.
By using either of these two methods, you can easily retrieve the current package version. The choice depends on your specific needs and use case. Typically, inspecting the package.json file is the most straightforward method, while using the npm list command allows you to quickly view the version without opening the file.