Skip to content

module.parent or require.main or process.mainModule for checking if a file is being run as a script? #9705

@semiphore

Description

@semiphore

Docs recommend using require.main === module: https://nodejs.org/api/all.html#modules_accessing_the_main_module

Some of the tests use require.main: https://github.com/nodejs/node/blob/master/test/fixtures/not-main-module.js#L2

But other tests check module.parent: https://github.com/nodejs/node/blob/master/test/parallel/test-cli-eval.js#L2-L3

And other tests check process.mainModule: https://github.com/nodejs/node/blob/master/test/fixtures/not-main-module.js#L2

Which is the preferred method? Also, the docs suggest that it may be possible for process.mainModule to be different from require.main, but there is no test that elicits the behavior. Should that be added to the test suite?

Metadata

Metadata

Assignees

No one assigned

    Labels

    moduleIssues and PRs related to the module subsystem.questionIssues that look for answers.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions