Search code examples
javascriptnode.jsnode-moduleses6-modules

detect whether ES Module is run from command line in Node


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

    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
    }