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

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!


Solution 1:

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

Solution 2:

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

Solution 3:

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

Solution 4:

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