我想检查我的模块是否被包含或直接运行。如何在 node.js 中做到这一点?
最佳答案
The docs描述另一种可能是首选方法的方法:
When a file is run directly from Node, require.main is set to its module.
要利用这一点,请检查此模块是否是主模块,如果是,请调用您的主代码:
function myMain() {
// main code
}
if (require.main === module) {
myMain();
}
编辑:如果您在浏览器中使用此代码,您将收到“引用错误”,因为未定义“require”。为防止这种情况,请使用:
if (typeof require !== 'undefined' && require.main === module) {
myMain();
}
关于node.js 相当于 python 的 if __name__ == '__main__',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4981891/