Check If Node.js File is Imported or Run as CLI
How to check if a Node.js (ESM) program is being executed on the command line or when imported by a Node.js process.
Use argv
to find Node's entry
and compare it to the current filename. If this is script.js
:
import { argv } from 'node:process'
import { fileURLToPath } from 'node:url'
const FILE = fileURLToPath(import.meta.url)
const isCLI = FILE === argv[1]
And this is main.js
:
import script from './script.js'
In my testing, the following is consistent:
node script.js # isCLI => true
node main.js # isCLI => false
from Sanity.io (142.82ms) to HTML (1.05ms)