Skip to content

Instantly share code, notes, and snippets.

@lmammino
Created June 29, 2021 17:32
Show Gist options
  • Select an option

  • Save lmammino/7dd898cf7ecfc6ec01e9cfaaa742e11e to your computer and use it in GitHub Desktop.

Select an option

Save lmammino/7dd898cf7ecfc6ec01e9cfaaa742e11e to your computer and use it in GitHub Desktop.
Modulino pattern in Node.js
const x = require('./index.js')
import a from './index.mjs'
if (require.main === module) {
console.log('called directly');
} else {
console.log('required as a module');
}
import { fileURLToPath } from 'url'
export default function () { }
const isRunningDirectlyViaCLI = process.argv[1] === fileURLToPath(import.meta.url)
if (isRunningDirectlyViaCLI) {
console.log('called directly');
} else {
console.log('required as a module');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment