I have a module which gets required
, but I temporarily don't want to run the code in the module. I could just comment it out, but then it got me wondering if there is a way to exit/return early from a loading module.
Is there a built in way to stop the execution flow through the module's code, and "return" early?
Actually, there is a built-in way. Every node module is loaded inside a module function wrapper and the module is executing as the body of that function. So you can just use a plain return
anywhere in the module to stop the rest of the code from executing.
Node modules get executed inside a function wrapper like this:
(function (exports, require, module, __filename, __dirname, process, global) {
// module code is here
// a return statement skips executing any more code in your module after that statement
return;
});
As such, you can just use a return
statement anywhere in the module and it will return from the module wrapper function, skipping the rest of the code in the module.
It is probably cleaner code to just use an if
statement or in your module to make the code a little more self describing and not leaving somebody wondering why there's an extraneous return
statement in the middle of a module:
// this code temporarily removed from being executed
if (someBoolean) {
// your module code here
}
Or just comment out a large section of code if you intend to remove it for awhile.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments