Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if package installed from within Node.js script

Tags:

node.js

I'm trying out Node.js for scripting.

I have a script, where I check the existence of ./node_modules/some-package. If it doesn't exist, some-package is installed.

This seems kind of hacky however.

Is there a better way to check if a particular package is installed from within the script?

sample code

const fs = require('fs');
let installed;

try {
  fs.accessSync('./node_modules/.bin/some-package');
  installed = true;
} catch (err) {
  installed = false;
}
like image 231
Colin Ricardo Avatar asked Jun 13 '18 15:06

Colin Ricardo


2 Answers

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

like image 156
Capricorn Avatar answered Oct 14 '22 04:10

Capricorn


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.

like image 43
Jason Cust Avatar answered Oct 14 '22 04:10

Jason Cust