admin管理员组

文章数量:1330564

I have a module which gets required, but I temporarily don't want to run the code in the module. I could just ment 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?

I have a module which gets required, but I temporarily don't want to run the code in the module. I could just ment 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?

Share Improve this question edited May 25, 2016 at 16:38 morsecoder asked May 25, 2016 at 16:33 morsecodermorsecoder 1,6592 gold badges17 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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 (at the top level - not in some other function) 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 ment out a large section of code if you intend to remove it for awhile.

There isn't a build-in way, but you can use the following workaround. Wrap the whole module in an IIFE and just use return statement:

(function() {

  // some code

  // stop execution here
  return;

  // some code

})()

本文标签: javascriptExit from loading Node module early without stopping processStack Overflow