When using CommonJS modules in Node, you can detect whether a script is being run from the command line using require.main === module
.
What is an equivalent way to detect whether a script is being run from the command line when using ES Modules in Node (with the --experimental-modules
flag)?
`import.meta.main` has been merged into Node.js v24: https://github.com/nodejs/node/pull/57804
So on Node.js v24 you can do this:
if (import.meta.main) {
// run directly as script
} else {
// imported into another script
}