Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions doc/api/esm.md
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,26 @@ hooks can provide this workflow in the future.

`require.cache` is not used by `import`. It has a separate cache.

### No `require.main`

To detect when an ES module is run directly with Node.js, it is possible to
compare the [`import.meta.url`][] value to the command line arguments. For
example:

```js
import { fileURLToPath } from 'url';
import process from 'process';

if (process.argv[1] === fileURLToPath(import.meta.url)) {
// The script was run directly.
}
```

The above approach does not cover the case where the script is run without the
`.js` extension (e.g. `node script` instead of `node script.js`). These cases
could be normalized by trimming any extension from the `import.meta.url` and
`process.argv[1]` values.

### URL-based paths

ES modules are resolved and cached based upon
Expand Down
4 changes: 4 additions & 0 deletions doc/api/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ 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 running [ECMAScript Modules][], `require.main` is not available. See the
ECMAScript Modules documentation for a possible [`require.main` alternative][].

## Addenda: Package manager tips

<!-- type=misc -->
Expand Down Expand Up @@ -1148,3 +1151,4 @@ consists of the following keys:
[`Error.prepareStackTrace(error, trace)`]: https://v8.dev/docs/stack-trace-api#customizing-stack-traces
[`SourceMap`]: modules.html#modules_class_module_sourcemap
[Source map v3 format]: https://sourcemaps.info/spec.html#h.mofvlxcwqzej
[`require.main` alternative]: esm.html#esm_no_require_main