简体   繁体   中英

Catch an error on requiring module in node.js

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.

For example:

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
}

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

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

}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM