在运行之前,我需要判断是否安装了"摩卡".我想出了以下代码:

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

我不喜欢抓住例外的 idea .有更好的办法吗?

推荐答案

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

the documentation for require.resolve

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

要求如果找不到模块,resolve()会抛出错误,所以您必须处理它.

Node.js相关问答推荐

MongoServelSelection错误:服务器 Select 在30000 ms后超时

如何修复PayPal Node.js Webhook中Webhook签名验证失败?''

当 Got 包因错误 JSON 崩溃时如何获取响应文本?

使用NodeJS通过服务账号列出Google Workspace用户

如何使用mongoose引用不在项目中的模型

如何在套接字对象中存储或添加数据?

如何使用填充在mongoose 上保存新数据

JAVASCRIPT:foreach 循环后的空数组

在 Express.js 中迭代子文档数组

Node.js 大文件上传到 MongoDB 阻塞了事件循环和工作池

如果 express.js (node.js) http 请求在完成之前关闭会发生什么?

fs.writefile 选项参数的可能值,尤其是只读文件的整数

突然 React 无法执行create-react-app命令.为什么会发生这种情况,我该如何解决?

为什么数组上的js映射会修改原始数组?

__dirname 未在 Node 14 版本中定义

请求新页面时如何将 AngularJS 路由与 Express (Node.js) 一起使用?

npm install - javascript堆内存不足

在 Node.js 中获取终端的宽度

用于轻松部署和更新的 Node.js 设置

如何阻止 babel 将this转换为undefined(并插入use strict)