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!
1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.
If the error is not resolved, try to delete your node_modules and package-lock. json (not package. json ) files, re-run npm install and restart your IDE. Copied!
If we want to handle the error for asynchronous code in Node. js then we can do it in the following two manners. Handle error using callback: A callback function is to perform some operation after the function execution is completed. We can call our callback function after an asynchronous operation is completed.
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)
}
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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With