node.js 相当于 python 的 if __name__ == '__main__'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4981891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 13:52:00  来源:igfitidea点击:

node.js equivalent of python's if __name__ == '__main__'

node.js

提问by nornagon

I'd like to check if my module is being included or run directly. How can I do this in node.js?

我想检查我的模块是否被包含或直接运行。我怎样才能在 node.js 中做到这一点?

回答by Stephen Emslie

The docsdescribe another way to do this which may be the preferred method:

文档描述了另一种方法,这可能是首选方法:

When a file is run directly from Node, require.main is set to its module.

当一个文件直接从 Node 运行时,require.main 被设置为它的模块。

To take advantage of this, check if this module is the main module and, if so, call your main code:

要利用这一点,请检查此模块是否是主模块,如果是,请调用您的主代码:

var fnName = function() {
    // main code
}

if (require.main === module) {
    fnName();
}

EDIT: If you use this code in a browser, you will get a "Reference error" since "require" is not defined. To prevent this, use:

编辑:如果您在浏览器中使用此代码,由于未定义“require”,您将收到“参考错误”。为了防止这种情况,请使用:

if (typeof require !== 'undefined' && require.main === module) {
    fnName();
}

回答by nornagon

if (!module.parent) {
  // this is the main module
} else {
  // we were require()d from somewhere else
}

EDIT: If you use this code in a browser, you will get a "Reference error" since "module" is not defined. To prevent this, use:

编辑:如果您在浏览器中使用此代码,您将收到“参考错误”,因为“模块”未定义。为了防止这种情况,请使用:

if (typeof module !== 'undefined' && !module.parent) {
  // this is the main module
} else {
  // we were require()d from somewhere else or from a browser
}