Check if a node.js module is available

前端 未结 5 1684
清酒与你
清酒与你 2020-11-30 09:29

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.

相关标签:
5条回答
  • 2020-11-30 10:08

    using ES6 arrow functions

    var modulePath = m => { try { return require.resolve(m) } catch(e) { return false } }
    
    0 讨论(0)
  • 2020-11-30 10:11

    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!
    }
    
    0 讨论(0)
  • 2020-11-30 10:18

    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
        }
    }
    
    0 讨论(0)
  • 2020-11-30 10:20

    Maybe resolve-like modules will be helpfully here?

    The numbers of modules are exist on npm:

    • async-resolve
    • resolve
    • resolveIt
    • enhanced-resolve
    • localizer

    I wrote first, async-resolve, and for example:

    var Resolver = require('async-resolve');
    var resolver_obj = new Resolver();
    resolver_obj.resolve('module', __dirname, function(err, filename) {
      return console.log(filename);
    });
    

    It use node modules path resolutions rules but don't block main loop as node do it. And in result you get filename, so it can be used to decide its local module or global and other things.

    0 讨论(0)
  • 2020-11-30 10:27

    ES6 simple solution with 1 line of code :

    const path = require('path');
    const fs = require('fs');
    
    function hasDependency(dep) {
            return module.paths.some(modulesPath => fs.existsSync(path.join(modulesPath, dep)));
    }
    
    0 讨论(0)
提交回复
热议问题