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


当前回答

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

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

为了利用这一点,检查这个模块是否是主模块,如果是,调用你的主代码:

function myMain() {
    // main code
}

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

编辑:如果你在浏览器中使用这段代码,你会得到一个“引用错误”,因为“要求”没有定义。为了防止这种情况,可以使用:

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

其他回答

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
}

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

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

为了利用这一点,检查这个模块是否是主模块,如果是,调用你的主代码:

function myMain() {
    // main code
}

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

编辑:如果你在浏览器中使用这段代码,你会得到一个“引用错误”,因为“要求”没有定义。为了防止这种情况,可以使用:

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