🏁 isMain & runIfMain
hbh-nodes provides utility functions to detect if a module is the main entry point and to execute code only when the module is run directly, not when imported. This is especially useful for libraries that can be both imported and executed as scripts.
Import
CommonJS
1const { isMain, runIfMain } = require("hbh-nodes");
ES Modules
1import { isMain, runIfMain } from "hbh-nodes";
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.
runIfMain(importMetaUrl, cjsModule, mainModule, fn)
Executes a function only if the current module is 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 (require.main). Optional but recommended in CommonJS. |
fn |
function |
Function to execute if the module is main. |
Returns
- Returns the result of
fn()if executed. - Returns
undefinedif the module is imported.
Behavior
- Calls
isMain()internally to determine if the module is the main entry point. - Executes the provided function
fn()only when the module is running directly. - Safe for mixed ESM + CommonJS environments.
Example
CommonJS
1const { runIfMain } = require("./mainCheck");3function main() {4 console.log("Running directly as a script!");5}7runIfMain(null, module, require.main, main);
ES Module
1import { runIfMain } from "./mainCheck.mjs";3runIfMain(import.meta.url, null, null, () => {4 console.log("Running directly in ESM!");5});
Edge Cases
- Does nothing if the module is imported.
- Safely handles invalid inputs.
- Useful for CLI scripts or libraries with optional initialization.
Best Practices
- Always pass the correct module references in CommonJS (
moduleandrequire.main). - For ESM, pass
import.meta.urlandnullfor the CommonJS parameters. - Wrap all startup code or CLI logic inside
runIfMainto avoid side effects on import. - Use
isMainif you need conditional checks without running a function.
Advanced / Deep Dive Usage
Example: CLI Script with Arguments
1runIfMain(import.meta.url, module, require.main, () => {2 const args = process.argv.slice(2);3 console.log("CLI arguments:", args);4 // Start your CLI logic here5});