node.js相当于python';s如果uuu name uuu==&x27__主&';

node.js相当于python';s如果uuu name uuu==&x27__主&';,node.js,Node.js,我想检查我的模块是否包括在内或直接运行。如何在node.js中执行此操作 if (!module.parent) { // this is the main module } else { // we were require()d from somewhere else } 编辑:如果在浏览器中使用此代码,则会出现“参考错误”,因为未定义“模块”。要防止出现这种情况,请使用: if (typeof module !== 'undefined' && !module.p

我想检查我的模块是否包括在内或直接运行。如何在node.js中执行此操作

if (!module.parent) {
  // this is the main module
} else {
  // we were require()d from somewhere else
}
编辑:如果在浏览器中使用此代码,则会出现“参考错误”,因为未定义“模块”。要防止出现这种情况,请使用:

if (typeof module !== 'undefined' && !module.parent) {
  // this is the main module
} else {
  // we were require()d from somewhere else or from a browser
}
if (typeof require !== 'undefined' && require.main === module) {
    fnName();
}
描述另一种可能是首选方法的方法:

当文件直接从节点运行时,require.main将设置为其模块

要利用此功能,请检查此模块是否为主模块,如果是,请调用主代码:

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

if (require.main === module) {
    fnName();
}
编辑:如果在浏览器中使用此代码,则会出现“引用错误”,因为未定义“require”。要防止出现这种情况,请使用:

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

这在什么地方有记录吗?没有,但在我的一个例子中使用了它。它比公认的答案读起来更好,并且具有不需要模块的“名称”的好处。公认的答案也不使用模块的名称。无论您的函数名如何,您始终必须检查require.main==模块。为了明确起见,上面的代码应该修改为:
var fnName=function(){//code}如果(require.main===module){fnName();}
我会用try…catch for browser将其包装起来compatibility@OhadCohen“try…catch”也可能捕捉到真正的错误。我认为最好只检查typeof是否需要!='“未定义”。但如果文件被分叉了怎么办?遗憾的是,这项功能随着
--实验模块
isMain
很快就会出现在您附近的node.js:)@DimaTisnek Source或有关
isMain
的更多信息而消失了?听起来很棒,但我找不到任何相关信息。我能找到的唯一重要参考资料是描述NPM在Node中对ESM模块的建议/愿景。我还没有从Node.js本身找到任何官方信息。任何链接将不胜感激