Skip to main content

ESM scripts can detect when they're run directly

CJS Node.js scripts have always been able to detect if they're running directly through the CLI or imported from another JS script through various means (the most recent being require.main === module).

However, ESM scripts have not been so lucky. For years the answer to this in ESM has simply been no.

Now it's in Node.js v24! You use it like this:

if (import.meta.main) {
// executed from CLI
} else {
// imported into another JS module
}