From c9bd1a7d8a8063523cbeaf1d5437663ea6b9103a Mon Sep 17 00:00:00 2001 From: Antoine du HAMEL Date: Wed, 11 Mar 2020 23:44:31 +0100 Subject: [PATCH] module: deprecate module.parent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This feature does not work when a module is imported using ECMAScript modules specification, therefore it is deprecated. Fixes: https://github.com/nodejs/modules/issues/469 PR-URL: https://github.com/nodejs/node/pull/32217 Backport-PR-URL: https://github.com/nodejs/node/pull/34592 Reviewed-By: Gus Caplan Reviewed-By: Bradley Farias Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Matteo Collina Reviewed-By: Tobias Nießen Reviewed-By: Ruben Bridgewater --- doc/api/deprecations.md | 35 +++++++++++++++++++++++++++++++++++ doc/api/modules.md | 14 ++++++++++++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index c2bac5198243f4..a12ca3dd7b5626 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -2560,6 +2560,41 @@ written twice. This introduces a race condition between threads, and is a potential security vulnerability. There is no safe, cross-platform alternative API. + +### DEP0144: `module.parent` + + +Type: Documentation-only + +A CommonJS module can access the first module that required it using +`module.parent`. This feature is deprecated because it does not work +consistently in the presence of ECMAScript modules and because it gives an +inaccurate representation of the CommonJS module graph. + +Some modules use it to check if they are the entry point of the current process. +Instead, it is recommended to compare `require.main` and `module`: + +```js +if (require.main === module) { + // Code section that will run only if current file is the entry point. +} +``` + +When looking for the CommonJS modules that have required the current one, +`require.cache` and `module.children` can be used: + +```js +const moduleParents = Object.values(require.cache) + .filter((m) => m.children.includes(module)); +``` + [`--http-parser=legacy`]: cli.html#cli_http_parser_library [`--pending-deprecation`]: cli.html#cli_pending_deprecation [`--throw-deprecation`]: cli.html#cli_throw_deprecation diff --git a/doc/api/modules.md b/doc/api/modules.md index 7cb5de8c4589e2..e8215a2ace67ed 100644 --- a/doc/api/modules.md +++ b/doc/api/modules.md @@ -894,11 +894,19 @@ loading. ### `module.parent` -* {module} +> Stability: 0 - Deprecated: Please use [`require.main`][] and +> [`module.children`][] instead. + +* {module | null | undefined} -The module that first required this one. +The module that first required this one, or `null` if the current module is the +entry point of the current process, or `undefined` if the module was loaded by +something that is not a CommonJS module (E.G.: REPL or `import`). ### `module.path`