Created
December 30, 2024 19:21
-
-
Save jrc03c/a354ca1fdcb3a6b9d8a47d7bfb8ce479 to your computer and use it in GitHub Desktop.
Check if JS script is being invoked directly in Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // In CommonJS format: | |
| if (require.main === module) { | |
| console.log("Invoked directly!") | |
| } | |
| // In ES module format: | |
| if (import.meta.url.includes(process.argv[1])) { | |
| console.log("Invoked directly!") | |
| } | |
| // CAVEAT: I don't actually how robust the ES module format is; it's just the | |
| // first solution that occurred to me. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment