ReferenceError: __dirname is not defined in ES module scope / __filename is not defined – Node.js DIRNAME_NOT_DEFINED_ESM

DIRNAME_NOT_DEFINED_ESM

Le costanti globali '__dirname' e '__filename' esistono solo in CommonJS; nei moduli ES si ricavano con 'import.meta.dirname' (Node 20.11+) o con 'fileURLToPath(new URL(".", import.meta.url))'.

Cosa significa questo errore?

Le costanti globali '__dirname' e '__filename' esistono solo in CommonJS; nei moduli ES si ricavano con 'import.meta.dirname' (Node 20.11+) o con 'fileURLToPath(new URL(".", import.meta.url))'.

Messaggio originale

ReferenceError: __dirname is not defined in ES module scope / __filename is not defined

Contesto e parole chiave

Alias

  • __dirname is not defined in ES module scope Node.js

Messaggi alternativi

  • variabili __dirname e __filename non definite in ESM

Prodotti

  • Node.js Runtime (v18 LTS, v20 LTS, v22 LTS, v24)

Piattaforme

  • Linux
  • macOS
  • Windows

Parole chiave

  • errore-nodejs-dirname-not-defined-es-module
  • javascript-backend
  • Moduli e CommonJS ed ESM
  • node
  • nodejs
  • nodejs.moduli.dirname-is-not-defined-in-es-module

Cause possibili

Causa tecnica per Errore Node.js: __dirname is not defined in ES module scope (Sostituto con import.meta.url)

Le costanti globali '__dirname' e '__filename' esistono solo in CommonJS; nei moduli ES si ricavano con 'import.meta.dirname' (Node 20.11+) o con 'fileURLToPath(new URL(".", import.meta.url))'.

molto comune

Diagnosi

Diagnostica di runtime o stack trace per Errore Node.js: __dirname is not defined in ES module scope (Sostituto con import.meta.url)

Eseguire Node.js con i flag diagnostici (--trace-warnings --trace-uncaught) per visualizzare l'origine dettagliata dell'eccezione.

Come leggere il risultato. Evidenzia il modulo esatto, la riga e lo stack trace della chiamata asincrona in errore.

terminal
node --trace-warnings --trace-uncaught app.js

Risoluzione

Risoluzione standard per Errore Node.js: __dirname is not defined in ES module scope (Sostituto con import.meta.url)

Difficoltà: mediaRischio: basso

Applicare la correzione al codice sorgente Node.js o alla configurazione del package.json.

  1. Ispezionare la riga evidenziata dal codice di errore o stack trace
  2. Aggiornare la sintassi di import/export, il controllo dei socket o la gestione della memoria
  3. Riavviare il processo Node.js o il demone di produzione (PM2/systemd) per verificare la stabilità
terminal
node app.js

Domande frequenti

Come risolvere l'errore Errore Node.js: __dirname is not defined in ES module scope (Sostituto con import.meta.url) in Node.js?

Le costanti globali '__dirname' e '__filename' esistono solo in CommonJS; nei moduli ES si ricavano con 'import.meta.dirname' (Node 20.11+) o con 'fileURLToPath(new URL(".", import.meta.url))'.

Approfondimenti

Schede correlate