Handle errors thrown by require() module in node.j

2019-02-21 09:12发布

having a bit of a snag in my code when trying to require() modules that don't exists. The code loops through a directory and does a var appname = require('path') on each folder. This works for appropriately configured modules but throws: Error: Cannot find module when the loop hits a non-module.

I want to be able to handle this error gracefully, instead of letting it stop my entire process. So in short, how does one catch an error thrown by require()?

thanks!

4条回答
霸刀☆藐视天下
2楼-- · 2019-02-21 09:59

looks like a try/catch block does the trick on this e.g.

try {
 // a path we KNOW is totally bogus and not a module
 require('./apps/npm-debug.log/app.js')
}
catch (e) {
 console.log('oh no big error')
 console.log(e)
}
查看更多
姐就是有狂的资本
3楼-- · 2019-02-21 09:59

If the issue is with files that don't exist, what you should do is:

let fs = require('fs');
let path = require('path');
let requiredModule = null; // or a default object {}

let pathToModule = path.join(__dirname, /* path to module */, 'moduleName');
if (fs.existsSync(pathToModule)) {
  requiredModule = require(pathToModule);
}

// This is in case the module is in node_modules
pathToModule = path.join(__dirname, 'node_modules', 'moduleName');
if (fs.existsSync(pathToModule)) {
  requiredModule = require(pathToModule);
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-21 10:00

Use a wrapper function:

function requireF(modulePath){ // force require
    try {
     return require(modulePath);
    }
    catch (e) {
     console.log('requireF(): The file "' + modulePath + '".js could not be loaded.');
     return false;
    }
}

Usage:

requireF('./modules/non-existent-module');

Based on OP answer of course

查看更多
叼着烟拽天下
5楼-- · 2019-02-21 10:12

If the given path does not exist, require() will throw an Error with its code property set to 'MODULE_NOT_FOUND'.

https://nodejs.org/api/modules.html#modules_file_modules

So do a require in a try catch block and check for error.code == 'MODULE_NOT_FOUND'

var m;
try {
    m = require(modulePath);
} catch (e) {
    if (e.code !== 'MODULE_NOT_FOUND') {
        throw e;
    }
    m = backupModule;
}
查看更多
登录 后发表回答