From 07cc4baf929f7190b699d4973a1c36ec613a5e34 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Mon, 3 Jan 2022 00:55:18 +0100 Subject: [PATCH 1/2] doc: document that `require.main` may be `undefined` --- doc/api/modules.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/doc/api/modules.md b/doc/api/modules.md index 264303006ae224..1a7db408f6d02e 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -74,9 +74,10 @@ run directly by testing `require.main === module`. For a file `foo.js`, this will be `true` if run via `node foo.js`, but `false` if run by `require('./foo')`. -Because `module` provides a `filename` property (normally equivalent to -`__filename`), the entry point of the current application can be obtained -by checking `require.main.filename`. +When the entry point is not a CommonJS module, `require.main` is `undefined`, +and the main module is out of reach. You can try to make assumptions based on +`process.cwd()` and `process.argv[1]` values to figure out the entry point of +the current application. ## Package manager tips @@ -718,10 +719,11 @@ extensions gets slower with each registered extension. added: v0.1.17 --> -* {module} +* {module | undefined} The `Module` object representing the entry script loaded when the Node.js -process launched. +process launched, or `undefined` if the entry point of the program is not a +CommonJS module. See ["Accessing the main module"](#accessing-the-main-module). In `entry.js` script: From d66a3b590ca30efd66ed41bb6a94bb8b3514892a Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Mon, 3 Jan 2022 19:37:16 +0100 Subject: [PATCH 2/2] Remove unreliable suggestion --- doc/api/modules.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/doc/api/modules.md b/doc/api/modules.md index 1a7db408f6d02e..e8f0788ceba960 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -75,9 +75,7 @@ For a file `foo.js`, this will be `true` if run via `node foo.js`, but `false` if run by `require('./foo')`. When the entry point is not a CommonJS module, `require.main` is `undefined`, -and the main module is out of reach. You can try to make assumptions based on -`process.cwd()` and `process.argv[1]` values to figure out the entry point of -the current application. +and the main module is out of reach. ## Package manager tips