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?
const fs = require('fs');
let installed;
try {
fs.accessSync('./node_modules/.bin/some-package');
installed = true;
} catch (err) {
installed = false;
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With