Today I learned: How to programmatically detect if a Node.js script is called from the command line or being imported

There are a CommonJS way and a ES module way to programmatically detect if a Node.js script is called from the command line (CLI) or being imported via respectively a require or an import statement.

CommonJS way

This one is super straightforward and officially documented (see: Accessing the main module).

It uses require.main and module as shown in the code snippet below:

const isCalledFromCommandLine = require.main === module;
const isCalledFromRequire = !isCalledFromCommandLine;

console.log({ isCalledFromCommandLine, isCalledFromRequire });

if (isCalledFromCommandLine) {
  // ...
}

// ...

if (isCalledFromRequire) {
  // ...
}

ES module way

This one is a bit more involved than the CommonJS way but goes like this:

import { resolve } from "node:path";
import { fileURLToPath } from "node:url";

const pathToThisFile = resolve(fileURLToPath(import.meta.url));
const pathPassedToNode =
  process.argv.length > 1 ? resolve(process.argv[1]) : undefined;

const isCalledFromCommandLine = pathToThisFile.includes(pathPassedToNode);
const isCalledFromImport = !isCalledFromCommandLine;

console.log({ isCalledFromCommandLine, isCalledFromImport });

if (isCalledFromCommandLine) {
  // ...
}

// ...

if (isCalledFromImport) {
  // ...
}

Note:

  • resolve() is used to handle symlinks
  • includes() is used to handle cases where the file extension was omitted when passed to node

Source - https://stackoverflow.com/a/66309132
Posted by seanCodes, modified by community. See post 'Timeline' for change history
Retrieved 2026-06-17, License - CC BY-SA 4.0