modules: deprecate module.parent by aduh95 · Pull Request #32217 · nodejs/node · GitHub
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
33 changes: 33 additions & 0 deletions doc/api/deprecations.md
13 changes: 10 additions & 3 deletions doc/api/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -690,7 +690,6 @@ Module {
id: '.',
path: '/absolute/path/to',
exports: {},
parent: null,
filename: '/absolute/path/to/entry.js',
loaded: false,
children: [],
Expand Down Expand Up @@ -894,11 +893,17 @@ loading.
### `module.parent`
<!-- YAML
added: v0.1.16
deprecated: REPLACEME
-->

* {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`). Read only.

### `module.path`
<!-- YAML
Expand Down Expand Up @@ -1122,13 +1127,15 @@ consists of the following keys:
[`createRequire()`]: #modules_module_createrequire_filename
[`module` object]: #modules_the_module_object
[`module.id`]: #modules_module_id
[`module.children`]: #modules_module_children
[`path.dirname()`]: path.html#path_path_dirname_path
[ECMAScript Modules]: esm.html
[an error]: errors.html#errors_err_require_esm
[exports shortcut]: #modules_exports_shortcut
[module resolution]: #modules_all_together
[module wrapper]: #modules_the_module_wrapper
[native addons]: addons.html
[`require.main`]: #modules_require_main
[source map include directives]: https://sourcemaps.info/spec.html#h.lmz475t4mvbx
[`--enable-source-maps`]: cli.html#cli_enable_source_maps
[`NODE_V8_COVERAGE=dir`]: cli.html#cli_node_v8_coverage_dir
Expand Down
21 changes: 18 additions & 3 deletions lib/internal/modules/cjs/loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ const {
ReflectSet,
RegExpPrototypeTest,
SafeMap,
SafeWeakMap,
String,
StringPrototypeIndexOf,
StringPrototypeMatch,
Expand Down Expand Up @@ -159,11 +160,12 @@ function updateChildren(parent, child, scan) {
children.push(child);
}

const moduleParentCache = new SafeWeakMap();
function Module(id = '', parent) {
this.id = id;
this.path = path.dirname(id);
this.exports = {};
this.parent = parent;
moduleParentCache.set(this, parent);
updateChildren(parent, this, false);
this.filename = null;
this.loaded = false;
Expand Down Expand Up @@ -232,6 +234,18 @@ ObjectDefineProperty(Module, 'wrapper', {
}
});

function getModuleParent() {
return moduleParentCache.get(this);
}
ObjectDefineProperty(Module.prototype, 'parent', {
get: pendingDeprecation ? deprecate(
getModuleParent,
'module.parent is deprecated due to accuracy issues. Please use ' +
'require.main to find program entry point instead.',
'DEP0143'
) : getModuleParent
});

const debug = require('internal/util/debuglog').debuglog('module');
Module._debug = deprecate(debug, 'Module._debug is deprecated.', 'DEP0077');

Expand Down Expand Up @@ -1018,7 +1032,7 @@ Module._resolveFilename = function(request, parent, isMain, options) {
const requireStack = [];
for (let cursor = parent;
cursor;
cursor = cursor.parent) {
cursor = moduleParentCache.get(cursor)) {
requireStack.push(cursor.filename || cursor.id);
}
let message = `Cannot find module '${request}'`;
Expand Down Expand Up @@ -1211,7 +1225,8 @@ Module._extensions['.js'] = function(module, filename) {
const pkg = readPackageScope(filename);
// Function require shouldn't be used in ES modules.
if (pkg && pkg.data && pkg.data.type === 'module') {
const parentPath = module.parent && module.parent.filename;
const parent = moduleParentCache.get(module);
const parentPath = parent && parent.filename;
const packageJsonPath = path.resolve(pkg.path, 'package.json');
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
}
Expand Down
4 changes: 2 additions & 2 deletions test/common/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ if (process.argv.length === 2 &&
!process.env.NODE_SKIP_FLAG_CHECK &&
isMainThread &&
hasCrypto &&
module.parent &&
require.main &&
require('cluster').isMaster) {
// The copyright notice is relatively big and the flags could come afterwards.
const bytesToRead = 1500;
const buffer = Buffer.allocUnsafe(bytesToRead);
const fd = fs.openSync(module.parent.filename, 'r');
const fd = fs.openSync(require.main.filename, 'r');
const bytesRead = fs.readSync(fd, buffer, 0, bytesToRead);
fs.closeSync(fd);
const source = buffer.toString('utf8', 0, bytesRead);
Expand Down
2 changes: 1 addition & 1 deletion test/common/require-as.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable node-core/require-common-first, node-core/required-modules */
'use strict';

if (module.parent) {
if (require.main !== module) {
const { spawnSync } = require('child_process');

function runModuleAs(filename, flags, spawnOptions, role) {
Expand Down
2 changes: 1 addition & 1 deletion test/js-native-api/test_instance_data/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
const common = require('../../common');
const assert = require('assert');

if (module.parent) {
if (module !== require.main) {
// When required as a module, run the tests.
const test_instance_data =
require(`./build/${common.buildType}/test_instance_data`);
Expand Down
2 changes: 1 addition & 1 deletion test/node-api/test_instance_data/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

const common = require('../../common');

if (module.parent) {
if (module !== require.main) {
// When required as a module, run the tests.
const test_instance_data =
require(`./build/${common.buildType}/test_instance_data`);
Expand Down
2 changes: 1 addition & 1 deletion test/parallel/test-cli-eval.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE.

'use strict';
if (module.parent) {
if (module !== require.main) {
// Signal we've been loaded as a module.
// The following console.log() is part of the test.
console.log('Loaded as a module, exiting with status code 42.');
Expand Down
14 changes: 14 additions & 0 deletions test/parallel/test-module-parent-deprecation.js