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)?
Use
if (import.meta.url === `file://${process.argv[1]}`) {
// module was not imported but called directly
}
See the MDN docs on import.meta
for details.
Better to use pathToFileURL
which handles forward/backward slashes on Unix vs Windows correctly (via Rich Harris)
import { pathToFileURL } from 'url'
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
// module was not imported but called directly
}