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 ?
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.
NodeJS: How to Load a Module with require() We always use the NodeJS require() function to load modules in our projects.
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.
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); }
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.
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