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

Created on 20 Nov 2016  路  2Comments  路  Source: nodejs/node

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?

module question

All 2 comments

If the docs recommend using require.main, then I'd use that.

If you want to add tests where you think they are missing, feel free to open a PR!

This issue has been inactive for sufficiently long that it seems like perhaps it should be closed. Feel free to re-open (or leave a comment requesting that it be re-opened) if you disagree. I'm just tidying up and not acting on a super-strong opinion or anything like that.

Was this page helpful?
0 / 5 - 0 ratings