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.