'How To Check If Node EsModule Was Imported Or Ran Directly

Node.js 13 recently rolled out an experimental ESModule loader, starting to take the switch away from CommonJS. However, code ran in an ESModule in Node.js isn't provided a require function, instead requiring the use of the new import syntax.

My problem is that typically the way to find out if a module was loaded via an import or ran directly from the command line requires the require function to be provided, because it check's require's main property against the current module's module object. Since require isn't provided in an ESModule in Node.js, how do I check if my ESModule was imported or ran directly from the command line?



Solution 1:[1]

given that you have "some function" that you want to export or run if your module is invoked directly, via node my-script.js,

// my-script.js
export async function myTask() {
  console.log('hi');
}

You can run myTask via adding:

import { createRequire } from 'module';
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)

// existing
export async function myTask() {
  console.log('hi');
}
// end existing

let entryFile = process.argv?.[1];

if (entryFile === __filename) {
  myTask();
}

this way, other scripts can

import { myTask } from './my-script.js';

without invoking myTask immediately, as you'd want when invoking from the CLI with node

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NullVoxPopuli