santifer/career-ops · error · TypeError

isMainModule expects import.meta.url; got

Error message

isMainModule expects import.meta.url; got ${typeof moduleUrl === 'string' ? 'an empty string' : typeof moduleUrl}

What it means

isMainModule() determines whether the module it is called from is the entry point `node` was launched with, and requires its argument to be a non-empty string representing import.meta.url. This TypeError fires when the argument is not a string at all (undefined, null, a number) or is an empty string — i.e. the caller did not pass import.meta.url.

Solutions

  1. Pass import.meta.url exactly: `if (isMainModule(import.meta.url)) { ... }`.
  2. If you have a filesystem path, convert it first: `pathToFileURL(__filename).href`.
  3. In a CJS context, switch the file to ESM or use the CJS equivalent (`require.main === module`) instead.

Example fix

// before
if (isMainModule(import.meta.filename)) { cli(); }
// after
import { pathToFileURL } from 'node:url';
if (isMainModule(import.meta.url)) { cli(); }
Defensive patterns

Strategy: type-guard

Validate before calling

if (typeof import.meta?.url !== 'string' || import.meta.url === '') {
  throw new Error('not running as ESM; isMainModule needs import.meta.url');
}
if (isMainModule(import.meta.url)) cli();

Type guard

const canCheckMain = (meta) => typeof meta?.url === 'string' && meta.url !== '';

Try / catch

try {
  if (isMainModule(import.meta.url)) cli();
} catch (err) {
  if (err instanceof TypeError && err.message.includes('isMainModule expects')) {
    console.error('Pass import.meta.url, not filename/path.');
  } else throw err;
}

Prevention

When it happens

Trigger: Calling isMainModule() with no argument, with import.meta.filename, with __filename-like values that are undefined in ESM, or with an empty-string variable; also calling from a context without import.meta (CommonJS interop).

Common situations: Copy-pasting the guard into a file and forgetting the argument; refactor renamed the variable holding import.meta.url leaving it undefined; using the helper in a CJS file where import.meta does not exist.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of santifer/career-ops@aac998c7ed (2026-09-16). Data as JSON: /api/errors/7f8b07fbb2e6f52e. Report an issue: GitHub.

Appendix: source

Thrown at lib/is-main-module.mjs:81

 */
const canonicalize = realpathSync.native ?? realpathSync;

/**
 * True when the module identified by `moduleUrl` is the process entrypoint.
 *
 * Call it as `isMainModule(import.meta.url)`. Returns false when the module was
 * imported rather than run, which is what keeps a CLI tail from firing inside
 * `node --test`, `test-all.mjs`, or any script that imports the module's
 * exported functions.
 *
 * @param {string} moduleUrl - The caller's `import.meta.url`. A `file:` URL, and
 *   deliberately nothing else — see the throw below.
 * @returns {boolean} True when this module is what `node` was pointed at.
 * @throws {TypeError} When handed a filesystem path instead of a `file:` URL.
 */
export function isMainModule(moduleUrl) {
  if (typeof moduleUrl !== 'string' || moduleUrl === '') {
    throw new TypeError(`isMainModule expects import.meta.url; got ${typeof moduleUrl === 'string' ? 'an empty string' : typeof moduleUrl}`);
  }

  if (!moduleUrl.startsWith('file:')) {
    // A Windows drive letter parses as a one-character URL scheme, so it has to
    // be excluded before the scheme test or `C:\co\pdf.mjs` reads as a URL.
    //
    // Matched WITHOUT requiring a following separator, because `C:repo\pdf.mjs`
    // is also a path — the drive-RELATIVE form, resolved against the current
    // directory on C:. Requiring `[\\/]` let that one through to the `return
    // false` below, which is the silent-suppression footgun this branch exists
    // to prevent. No registered URL scheme is a single letter, so treating
    // `X:` as a drive is unambiguous.
    const isPath = !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(moduleUrl) || /^[a-zA-Z]:/.test(moduleUrl);
    if (isPath) {
      // LOUD, because the quiet alternative is the bug this module exists to
      // kill. `isMainModule(import.meta.filename)` would resolve, compare
      // false, skip the CLI tail, and exit 0 having printed nothing — #3170
      // reintroduced one argument at a time. A crash names the mistake instead.

View on GitHub (pinned to aac998c7ed)