Check if package installed from within Node.js script

I believe the NPM docs have what you are looking for:

optionalDependencies

If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the optionalDependencies object. This is a map of package name to version or url, just like the dependencies object. The difference is that build failures do not cause installation to fail.

It is still your program's responsibility to handle the lack of the dependency. For example, something like this:

try {
  var foo = require('foo')
  var fooVersion = require('foo/package.json').version
} catch (er) {
  foo = null
}
if ( notGoodFooVersion(fooVersion) ) {
  foo = null
}

// .. then later in your program ..

if (foo) {
  foo.doFooThings()
}

Entries in optionalDependencies will override entries of the same name in dependencies, so it's usually best to only put in one place.


One problem with the question's approach could be, that the path of the node_modules folder may be changed (npm local install package to custom location).

One way to utilize npm for getting information about installed packages is via npm ls.

The following call will return the installed version of some-package:

npm ls some-package

In case the package exists, it will print the version information, otherwise (empty). Make use of the --json cli-flag in case you want to parse the response.

If you're interested whether the package exists or not, you may just use the exit code: it's 0 if the package exists and non-zero otherwise.*

Bonus: Refer to Execute a command line binary with Node.js on how to execute shell commands from nodejs.

Source: Find the version of an installed npm package, https://docs.npmjs.com/cli/ls

*At least for me with node 5.6.0

Tags:

Node.Js