Check if a node.js module is available

前端 未结 5 1712
清酒与你
清酒与你 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: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
        }
    }
    

提交回复
热议问题