Node.js-检查是否实际安装了模块 [英] Node.js - check if module is installed without actually requiring it

查看:143
本文介绍了Node.js-检查是否实际安装了模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to check whether "mocha" is installed, before running it. I came up with the following code:

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);
}

我不喜欢这个例外的想法.有更好的方法吗?

I dont like the idea to catch an exception. Is there a better way?

推荐答案

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

You should use require.resolve() instead of require(). require will load the library if found, but require.resolve() will not, it will return the file name of the module.

请参见 require.resolve文档

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

如果找不到模块,则

require.resolve()确实会引发错误,因此您必须对其进行处理.

require.resolve() does throw error if module is not found so you have to handle it.

这篇关于Node.js-检查是否实际安装了模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆