From bbc059378bbb1b0a415472fdf44edfa8f675b9a4 Mon Sep 17 00:00:00 2001 From: Joe <28568841+Lordfirespeed@users.noreply.github.com> Date: Mon, 26 May 2025 23:31:54 +0100 Subject: [PATCH] esm: implement import.meta.main Boolean value to check if an ES Module is the entrypoint of the current process. Implements: #57226 Co-authored-by: Antoine du Hamel PR-URL: https://github.com/nodejs/node/pull/57804 Fixes: https://github.com/nodejs/node/issues/57226 Reviewed-By: James M Snell Reviewed-By: Matteo Collina Reviewed-By: Guy Bedford Reviewed-By: Antoine du Hamel Reviewed-By: Marco Ippolito --- doc/api/esm.md | 34 +++++++++ lib/internal/main/worker_thread.js | 14 ++++ .../modules/esm/initialize_import_meta.js | 6 +- lib/internal/modules/esm/loader.js | 8 +- lib/internal/modules/esm/translators.js | 3 +- lib/internal/modules/esm/utils.js | 12 ++- lib/internal/worker.js | 5 +- .../test-esm-import-meta-main-eval.mjs | 74 +++++++++++++++++++ test/es-module/test-esm-import-meta-main.mjs | 26 +++++++ test/es-module/test-esm-import-meta.mjs | 2 +- test/fixtures/es-modules/import-meta-main.mjs | 1 + 11 files changed, 173 insertions(+), 12 deletions(-) create mode 100644 test/es-module/test-esm-import-meta-main-eval.mjs create mode 100644 test/es-module/test-esm-import-meta-main.mjs create mode 100644 test/fixtures/es-modules/import-meta-main.mjs diff --git a/doc/api/esm.md b/doc/api/esm.md index 707eb9d41d..1bc7de2259 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -400,6 +400,35 @@ import { readFileSync } from 'node:fs'; const buffer = readFileSync(new URL('./data.proto', import.meta.url)); ``` +### `import.meta.main` + + + +> Stability: 1.0 - Early development + +* {boolean} `true` when the current module is the entry point of the current process; `false` otherwise. + +Equivalent to `require.main === module` in CommonJS. + +Analogous to Python's `__name__ == "__main__"`. + +```js +export function foo() { + return 'Hello, world'; +} + +function main() { + const message = foo(); + console.log(message); +} + +if (import.meta.main) main(); +// `foo` can be imported from another module without possible side-effects from `main` +``` + ### `import.meta.resolve(specifier)`