Node.js - 检查是否安装了模块而没有实际需要它

And*_*eyM 43 module require node.js

在运行之前,我需要检查是否安装了"mocha".我想出了以下代码:

try {
    var mocha = require("mocha");
} catch(e) {
    console.error(e.message);
    console.error("Mocha is probably not found. Try running `npm install mocha`.");
    process.exit(e.code);
}
Run Code Online (Sandbox Code Playgroud)

我不喜欢捕捉异常的想法.有没有更好的办法?

use*_*109 72

你应该使用require.resolve()而不是require().require如果找到,将加载库,但require.resolve()不会,它将返回模块的文件名.

请参阅require.resolve的文档

try {
    console.log(require.resolve("mocha"));
} catch(e) {
    console.error("Mocha is not found");
    process.exit(e.code);
}
Run Code Online (Sandbox Code Playgroud)

如果找不到模块,require.resolve()会抛出错误,因此您必须处理它.

  • `require.resolve`仍然会抛出错误 - 这就是我想要避免的 - 捕获异常. (10认同)
  • 接受答案,因为其他解决方案在任何方面都不是更清洁. (3认同)