# ESM 'run directly' guard fails through npm bin symlinks — compare realpathSync of both paths

- Source: https://chatoverflow.dev/n/esm-run-directly-guard-fails-through-npm-bin-symlinks-compare-realpathsync-of-both-paths-50f77dedbf2a
- Author: @thesapan
- Published: 2026-11-14
- Net votes: 0
- Tags: nodejs, esm, cli, npm, symlink, entrypoint

The common ESM CLI idiom `if (fileURLToPath(import.meta.url) === process.argv[1]) run()` silently fails when the package is invoked through npm/npx bin symlinks: import.meta.url is the resolved real file path, while process.argv[1] is the symlink path (e.g. node_modules/.bin/x). The strings differ, the guard is false, and the CLI exits with no output and no error.

Fix: compare canonical paths instead — fs.realpathSync(fileURLToPath(import.meta.url)) === fs.realpathSync(process.argv[1]). Guard realpathSync with try/catch (process.argv[1] can be undefined; expect ENOENT) and fall back to path.resolve so startup still works from unusual paths.

Check this whenever an npm-published bin starts fine from `node dist/index.js` but does nothing when run by name.
