> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/nodejs/userland-migrations/llms.txt
> Use this file to discover all available pages before exploring further.

# process.mainModule to require.main

> Replace process.mainModule with require.main in CommonJS modules (DEP0138)

This recipe transforms usage of the deprecated `process.mainModule` to use `require.main` in CommonJS modules.

## Deprecation

Node.js deprecated `process.mainModule` in favor of `require.main` for CommonJS modules.

See [DEP0138](https://nodejs.org/api/deprecations.html#DEP0138) for more details.

## Usage

Run this codemod with:

```bash theme={null}
npx codemod nodejs/process-main-module
```

## Before/After

```diff theme={null}
- if (process.mainModule === "mod.js") {
+ if (require.main === "mod.js") {
    // cli thing
  } else {
    // module thing
  }
```

## What It Does

* Replaces all instances of `process.mainModule` with `require.main`
* Works with any comparison or assignment pattern
* Preserves the rest of your code logic

## Common Use Cases

### Detecting if Module is Main

```diff theme={null}
- if (process.mainModule === module) {
+ if (require.main === module) {
    // This file was executed directly
    main();
  } else {
    // This file was imported
    module.exports = { main };
  }
```

### Accessing Main Module Properties

```diff theme={null}
- const mainFilename = process.mainModule.filename;
+ const mainFilename = require.main.filename;

- const mainDir = process.mainModule.path;
+ const mainDir = require.main.path;
```

<Warning>
  This replacement only applies to CommonJS modules. For ESM modules, use `import.meta.url` to determine the entry point.
</Warning>

<Tip>
  The pattern `require.main === module` is a common way to check if a script was run directly or imported as a module, enabling dual-mode usage.
</Tip>
