NodeJS: How to write a file that can run as a script or be imported/required as a module

If you are familiar with Python, you have probably seen the good old if __name__ == '__main__'. This line allows your program to know the context in which it is running and make slight adjustments based on it.

The most common use case is the following:

  1. If file is being used by the interpreter, just run a specific function.
  2. If file is being imported by another file, export function without running it.

There is quite a few reasons one would want to have this functionality. Testing CLI scripts and DRY ad-hoc runs of specific portions of a larger application are the ones that I encounter the most.

Bellow is a primer for how this can easily be done in JavaScript.

async function run() {
  console.log('Simulating async stuff');

if (require.main === module) {
  // File is being used as a script. Run it.
} else {
  // File is being used as a module. Export it.
  module.exports = { run };

const { run } = require('./my-file');