javascript - Exit from loading Node module early without stopping process - Stack Overflow

I have a module which gets required, but I temporarily don't want to run the code in the module. I

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

})()

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742273531a4413152.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信