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

Javascriptnode.jsError Handling

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

> 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 - Javascript

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 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbhurlowView Question on Stackoverflow
Solution 1 - JavascriptbhurlowView Answer on Stackoverflow
Solution 2 - JavascriptadiktofsugarView Answer on Stackoverflow
Solution 3 - JavascriptDaniGuardiolaView Answer on Stackoverflow
Solution 4 - JavascriptMor ShemeshView Answer on Stackoverflow