isMain(importMetaUrl, cjsModule, mainModule)
Determines if the current module is being executed as the main script.
Parameters
| Name | Type | Description |
|---|---|---|
importMetaUrl |
string |
URL |
cjsModule |
object |
The CommonJS module object. Optional if using ESM. |
mainModule |
object |
The main module reference, typically require.main. Optional but recommended in CommonJS. |
Returns
true→ If the module is the main entry point.false→ If the module is imported or parameters are invalid.
Behavior
-
CommonJS Detection:
1if (typeof mainModule !== "undefined" && cjsModule === mainModule) {2 return require.main === mainModule;3}Checks if the current
moduleis the main script. -
ES Module Detection:
1const filename = fileURLToPath(importMetaUrl);2return filename === process.argv[1];Converts
import.meta.urlto a path and compares with the Node.js entry file. -
Safe Fallback: Returns
falsefor unknown or invalid inputs.
Example
1const { isMain } = require("./mainCheck");3if (isMain(null, module, require.main)) {4 console.log("This module is running directly!");5}
Edge Cases
- Works for both ES modules and CommonJS.
- Returns
falsewhen the module is imported. - Handles invalid inputs gracefully.
- In ESM,
requireis unavailable, so CommonJS checks are skipped.