What’s the best way to check if a specific version of an npm package is installed globally and update the package only if needed?

I want to write a script (PowerShell or similar) to help sys-engineers integrate the Karma test runner into TeamCity. The script should:

Read the desired Karma version from a config file (possibly as a comment in karma.conf.js).

Check if that version is installed globally.

If not installed or outdated, use npm update package logic to fetch the correct version.

Run the test command:

karma start .\Scripts-Tests\karma.conf.js --reporters teamcity --single-run I don’t want to reinstall every time, since changing versions might break compatibility with config values.

I’ve worked with similar PowerShell setups to integrate Karma with CI tools, and I totally understand the need to avoid reinstalling dependencies each time. One approach I use is to check for the global Karma version with npm list -g karma. If the package is not installed or the version doesn’t match the desired one, I simply use npm install -g karma@<desired-version>. This avoids unnecessary npm update package calls and ensures that the correct version is installed only when needed, keeping things predictable and stable across different environments. It’s been super reliable for me.

I agree with @joe-elmoufak’s method it’s a solid start. I also use it as a foundation, but I go a step further by reading the target Karma version from a comment in the karma.conf.js file using a quick regex in PowerShell. Then, I run npm ls -g karma --depth=0 --json, which makes parsing the installed version a bit easier. If the versions don’t match, I call npm install -g karma@<version> as you suggested. This keeps my setup clean and ensures I’m not reinstalling every time. The key is to avoid running npm update package unless it’s absolutely necessary, which helps maintain consistency and prevents unwanted updates.

@joe-elmoufak @emma-crepeau Both of your approaches are rock solid, I’ve used something very similar. But here’s a little addition I made: I added a fallback check with Get-Command karma to confirm that the Karma binary is actually available globally. It’s easy to assume that Karma is installed, but I’ve seen instances where it wasn’t, and that could throw things off. Once I verify it’s there, I use the version comparison as we’ve discussed and conditionally run npm update package with npm install -g karma@<version>. After ensuring the right version is installed, I then trigger the TeamCity-compatible test run exactly as you’ve shown:

karma start .\Scripts-Tests\karma.conf.js --reporters teamcity --single-run

That’s been working great for us since we added that extra conditional check.