356

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

nornagon
  • 15,393
  • 18
  • 71
  • 85
  • 2
    `isMain` coming soon to node.js near you :) – Dima Tisnek May 01 '20 at 02:29
  • 1
    @DimaTisnek Source or any more info on `isMain`? It sounds fantastic but I can't find anything about it – Ken Bellows Oct 02 '20 at 12:00
  • 1
    The only significant reference I can find is in [a Gist from CJ Silveiro](https://gist.github.com/ceejbot/b49f8789b2ab6b09548ccb72813a1054) describing NPM's proposal/vision for ESM modules in Node. I haven't been able to find anything official from Node.js themselves. Any links would be appreciated – Ken Bellows Oct 02 '20 at 12:15
  • https://exploringjs.com/nodejs-shell-scripting/ch_nodejs-path.html#detecting-if-module-is-main detecting if the current module is “main” (the app entry point) – aderchox Apr 20 '23 at 10:51

2 Answers2

467

The nodejs docs describe 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.

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

function myMain() {
    // main code
}

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

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

if (typeof require !== 'undefined' && require.main === module) {
    myMain();
}
Shlomo
  • 120
  • 2
  • 8
Stephen Emslie
  • 10,539
  • 9
  • 32
  • 28
69
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
}
nornagon
  • 15,393
  • 18
  • 71
  • 85