Categories
JavaScript Answers

How to check in Node if module exists and if exists to load?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *