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 badges2 Answers
Reset to default 8Actually, 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
版权声明:本文标题:javascript - Exit from loading Node module early without stopping process - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742273530a2444758.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论