在node.js中要求模块捕获错误 [英] Catch an error on requiring module in node.js

查看:101
本文介绍了在node.js中要求模块捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎找不到任何文章。我基本上想要从程序中捕获找不到模块错误,并且可以选择要求安装它,但是即使在我的require语句中也可以尝试一下,我似乎也看不到任何错误。这是甚么可能吗?我没有在任何地方看到它。

Can't seem to find any articles on this anywhere. I basically want to catch the "Cannot find module" error from within the program, and optionally ask to install it, but I can't seem to catch any errors even with a try/catch around my require statements. Is this even possible? I haven't seen it done anywhere.

例如:

try {
  var express = require('express');
} catch (err){
   console.log("Express is not installed.");
   //proceed to ask if they would like to install, or quit.
   //command to run npm install
}

我想这可能是使用没有任何第三方需要的单独的.js启动文件完成,只需使用 fs 来检查 node_modules ,以及然后选择从子进程运行 npm install ,然后运行 node app 与另一个孩子。但是,感觉就像在一个app.js文件中更容易做到这一点。

I suppose this could be done with a seperate .js startup file without any 3rd party requires, and simply uses fs to check for node_modules, and then optionally runs npm install from child process, then runs node app with another child. But it feels like it would be easier to do this from within a single app.js file

推荐答案

你拥有了它。你确定在需要查找的文件系统中没有 node_modules / express 文件夹在你的上方吗?尝试这样做是为了清楚发生了什么:

That works fine for me as you have it. Are you sure there's no node_modules/express folder somewhere above you in the filesystem that require is finding? Try doing this to be clear about what's happening:

try {
  var express = require('express');
  console.log("Express required with no problems", express);
} catch (err){
   console.log("Express is not installed.");
   //proceed to ask if they would like to install, or quit.
   //command to run npm install
}

这篇关于在node.js中要求模块捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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