Sometimes, we want to check in Node if module exists and if exists to load.
In this article, we’ll look at how to check in Node if module exists and if exists to load.
How to check in Node if module exists and if exists to load?
To check in Node if module exists and if exists to load, we can wrap our require
call with a try-catch block.
For instance, we write
try {
const m = require('/foo/bar');
// ...
} catch (ex) {
handleErr(ex);
}
to wrap our require
call with a try
block.
If the module doesn’t exist, then an error will be thrown, and so we can catch the error with the catch
block.
Conclusion
To check in Node if module exists and if exists to load, we can wrap our require
call with a try-catch block.