detect whether ES Module is run from command line in Node

Issue

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)?

Solution

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.

Update Sep 27, 2021

Perhaps more robust, but involving an extra import (via Rich Harris)

import url from 'url'

if (import.meta.url === url.pathToFileURL(process.argv[1]).href) {
  // module was not imported but called directly
}

Answered By – Casimir

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.