Check if a node.js module is available

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

提交回复
热议问题