0

How can I detect whether my node.js file was called directly from console (windows and unix systems) or loaded using the ESM module import (import {foo} from 'bar.js')

The question was already answered for regular node.js files (Detect if called through require or directly by command line) but since require is not available in .mjs files with --experimental-modules turned on, I am in need of a different solution.

mxcd
  • 1,954
  • 2
  • 25
  • 38

1 Answers1

1

Node.js does not currently expose that information to es modules, and it is not certain whether it ever will[0]. I'd say the safest option for now is to put your CLI logic into a separate file.

0: https://github.com/nodejs/modules/issues/274

snek
  • 1,980
  • 1
  • 15
  • 29