Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a node.js module is available

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.

like image 310
Florian Margaine Avatar asked Jul 22 '12 13:07

Florian Margaine


People also ask

How do I know if Node.js is available?

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.

How are Node.js modules available externally?

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.

Where can I find node_modules?

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.


2 Answers

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! } 
like image 163
Stijn de Witt Avatar answered Sep 20 '22 23:09

Stijn de Witt


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     } } 
like image 26
Florian Margaine Avatar answered Sep 22 '22 23:09

Florian Margaine