Skip to content

Instantly share code, notes, and snippets.

@jrc03c
Created December 30, 2024 19:21
Show Gist options
  • Save jrc03c/a354ca1fdcb3a6b9d8a47d7bfb8ce479 to your computer and use it in GitHub Desktop.
Save jrc03c/a354ca1fdcb3a6b9d8a47d7bfb8ce479 to your computer and use it in GitHub Desktop.
Check if JS script is being invoked directly in Node
// 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