Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to check if file/(custom)module js exists under some path. I tried like

var m = require('/home/test_node_project/per');
but it throws error when there is no per.js in path. I thought to check with fs if file exists but I don't want to add '.js' as suffix if is possible to check without that. How to check in node if module exists and if exists to load ?

like image 551
Damir Avatar asked Feb 12 '14 21:02

Damir


People also ask

How do I know if a node module is installed?

To check for all locally installed packages and their dependencies, navigate to the project folder in your terminal and run the npm list command. You can also check if a specific package is installed locally or not using the npm list command followed by package name.

Which function is used to load any module in node JS?

NodeJS: How to Load a Module with require() We always use the NodeJS require() function to load modules in our projects.

What is the use if node JS?

Node. js is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It's used for traditional web sites and back-end API services, but was designed with real-time, push-based architectures in mind.


2 Answers

Require is a synchronous operation so you can just wrap it in a try/catch.

try {     var m = require('/home/test_node_project/per');     // do stuff } catch (ex) {     handleErr(ex); } 
like image 136
Chev Avatar answered Oct 12 '22 02:10

Chev


You can just try to load it and then catch the exception it generates if it fails to load:

try {     var foo = require("foo"); } catch (e) {     if (e instanceof Error && e.code === "MODULE_NOT_FOUND")         console.log("Can't load foo!");     else         throw e; } 

You should examine the exception you get just in case it is not merely a loading problem but something else going on. Avoid false positives and all that.

like image 34
Louis Avatar answered Oct 12 '22 03:10

Louis