From 430e66b9b87012dd964eee3e3f91fdfad31d24bc 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 1/2] 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 Backport-PR-URL: https://github.com/nodejs/node/pull/58693 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 | 9 ++- 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, 174 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 14a87186aa2e9e..c7675dae16ab62 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -393,6 +393,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)`