How to determine whether a file has been run directly inside ES module
- Node.js Version: 12.6.0
- OS: Windows
- Scope (install, code, runtime, meta, other?): runtime, documentation
Current documentation says:
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.
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?
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.
ping @sosoba
@sosoba , were you able to follow @devsnek 's suggestion? or it is still an issue?
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 , thanks for the information. as nodejs/node#49440 is still open and under discussion, let us wait to its resolution
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.
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.
It works now! https://github.com/nodejs/node/pull/57804