As a Node.js developer, it’s often necessary to determine the version of an installed npm package. This can be useful for troubleshooting compatibility issues, updating dependencies, or simply verifying that a package is installed correctly. In this tutorial, we’ll explore several methods for finding the version of an installed npm package.
Using npm list
The npm list
command is a versatile tool for displaying information about installed packages. To find the version of a specific package, you can pass its name as an argument:
npm list grunt
This will output the version of the grunt
package, along with its dependencies:
projectName@projectVersion /path/to/project/folder
└── [email protected]
If you want to see the versions of all installed packages, simply run npm list
without any arguments:
npm list
This will display a tree-like structure showing the dependencies between packages.
To list only the top-level packages (without their dependencies), you can use the --depth=0
argument:
npm list --depth=0
This is useful when you have a large number of installed packages and want to quickly see which ones are outdated.
Using npm info
Another way to find the version of an installed package is by using the npm info
command:
npm info grunt version
This will output the version of the grunt
package.
Using node -p
If you’re already in the directory where the package is installed (e.g., node_modules/<package_name>
), you can use the node -p
command to print the version from the package.json
file:
node -p "require('./package.json').version"
Note that this method requires you to be in the correct directory, so you may need to navigate there using cd
before running the command.
Finding Globally Installed Packages
To find the versions of globally installed packages, you can use the -g
flag with npm list
:
npm list -g
This will display a list of all globally installed packages, along with their versions. You can also use the --depth=0
argument to list only top-level packages:
npm list -g --depth=0
Conclusion
In this tutorial, we’ve covered several methods for finding the version of an installed npm package. Whether you’re using npm list
, npm info
, or node -p
, it’s easy to determine which versions of your dependencies are installed. By mastering these techniques, you’ll be better equipped to manage your Node.js projects and troubleshoot any issues that may arise.