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 for more details.
Usage
Run this codemod with:
npx codemod nodejs/process-main-module
Before/After
- 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
- 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
- const mainFilename = process.mainModule.filename;
+ const mainFilename = require.main.filename;
- const mainDir = process.mainModule.path;
+ const mainDir = require.main.path;
This replacement only applies to CommonJS modules. For ESM modules, use import.meta.url to determine the entry point.
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.