I'm looking for a way to find out if a module is available.
For example, I want to check if the module mongodb
is available, programmatically.
Also, it shouldn't halt the program if a module isn't found, I want to handle this myself.
PS: I added this question because Google isn't helpful.
To see if Node is installed, open the Windows Command Prompt, Powershell or a similar command line tool, and type node -v . This should print a version number, so you'll see something like this v0.
js Package Manager (npm) is the default and most popular package manager in Node. js ecosystem that is primarily used to install and maintain external modules in Node. js application. Users can basically install the node modules needed for their application using npm.
On Unix systems they are normally placed in /usr/local/lib/node or /usr/local/lib/node_modules when installed globally. If you set the NODE_PATH environment variable to this path, the modules can be found by node. Non-global libraries are installed the node_modules sub folder in the folder you are currently in.
There is a more clever way if you only want to check whether a module is available (but not load it if it's not):
function moduleAvailable(name) { try { require.resolve(name); return true; } catch(e){} return false; } if (moduleAvailable('mongodb')) { // yeah we've got it! }
Here is the most clever way I found to do this. If anyone has a better way to do so, please point it out.
var mongodb; try { mongodb = require( 'mongodb' ); } catch( e ) { if ( e.code === 'MODULE_NOT_FOUND' ) { // The module hasn't been found } }
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