Catch an error on requiring module in node.js

為{幸葍}努か 提交于 2019-12-05 00:19:51

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
}

To make it right, make sure to catch only Module not found error for given module:

try {
    var express = require('express');
} catch (e) {
    if (e.code !== 'MODULE_NOT_FOUND') {
        // Re-throw not "Module not found" errors 
        throw e;
    }
    if (e.message.indexOf('\'express\'') === -1) {
        // Re-throw not found errors for other modules
        throw e;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!