DEV Community

Sanjar Afaq
Sanjar Afaq

Posted on

Detect file run as main or module

There's a simple way in Python to know if current file is being run directly or as an import, using the __main__ variable. Any such way in Node.js?

Yes, there is.

CommonJS

if (require.main === module) {
  console.log('This file is being run directly.');
} else {
  console.log('This file is being imported as a module.');
}
Enter fullscreen mode Exit fullscreen mode

ESM

// mainModule.mjs

if (import.meta.url === `file://${process.argv[1]}`) {
  console.log('This ESM module is being run directly.');
} else {
  console.log('This ESM module is being imported as a module.');
}
Enter fullscreen mode Exit fullscreen mode

What's the use of this?

I write Node.js scripts for personal use, and it's good to have usage examples that console.log something. If a script is being run directly, it'll print the usage examples, otherwise it'll stay silent.

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay