help icon indicating copy to clipboard operation
help copied to clipboard

How to determine whether a file has been run directly inside ES module

Open sosoba opened this issue 6 years ago • 5 comments

  • Node.js Version: 12.6.0
  • OS: Windows
  • Scope (install, code, runtime, meta, other?): runtime, documentation

Current documentation says:

  1. Accessing the main module:

When a file is run directly from Node.js, require.main is set to its module. That means that it is possible to determine whether a file has been run directly by testing require.main === module.

  1. Differences Between ES Modules and CommonJS:

These CommonJS variables are not available in ES modules.

The new challege is - how to determine whether a file has been run directly inside ES module?

sosoba avatar Jul 19 '19 19:07 sosoba

the concept of a main is mostly considered a mistake, so we haven't exposed such a thing to esm. It's generally considered best practice to have separate files for your bin and lib functionality.

devsnek avatar Jul 19 '19 19:07 devsnek

ping @sosoba

gireeshpunathil avatar Dec 21 '19 04:12 gireeshpunathil

@sosoba , were you able to follow @devsnek 's suggestion? or it is still an issue?

PoojaDurgad avatar Sep 16 '20 04:09 PoojaDurgad

Hi @PoojaDurgad.

Temporary I using:

import {pathToFileURL} from 'node:url';

if ( import.meta.url === pathToFileURL(process.argv[1]).href) {
    // Loaded as main module
}

but finally community proposing import.meta.main which looking god. Please merge with https://github.com/nodejs/node/issues/49440

sosoba avatar Sep 16 '20 05:09 sosoba

@sosoba , thanks for the information. as nodejs/node#49440 is still open and under discussion, let us wait to its resolution

PoojaDurgad avatar Sep 19 '20 12:09 PoojaDurgad

It seems there has been no activity on this issue for a while, and it is being closed in 30 days. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.

github-actions[bot] avatar Oct 27 '24 01:10 github-actions[bot]

It seems there has been no activity on this issue for a while, and it is being closed. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.

github-actions[bot] avatar Nov 26 '24 01:11 github-actions[bot]

It works now! https://github.com/nodejs/node/pull/57804

sosoba avatar Aug 12 '25 05:08 sosoba