Arreglar __dirname no definido en Módulos ES de Node.js

Descubre por qué __dirname no funciona en ES Modules y cómo solucionarlo con import.meta.url y fileURLToPath. Una guía práctica para migrar de CommonJS a ES Modules en Node.js, gestionar rutas de archivos con fs y aplicar buenas prácticas.

4 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Si has estado trabajando con Node.js y has pasado de CommonJS require a ES Modules import y export, es probable que te hayas topado con este error molesto: ReferenceError: __dirname is not defined in ES module scope.

El motivo es sencillo: en CommonJS, Node.js expone de forma automática variables especiales como __dirname y __filename para conocer la ruta del archivo actual o el directorio. En cambio, cuando usas ES Modules archivos .mjs o estableces type module en package.json, estas variables ya no están disponibles por defecto.

Entonces, ¿cómo solucionarlo de forma fiable y compatible con ES Modules? A continuación te explicamos el enfoque recomendado.

Por qué ocurre el error: en CommonJS, __dirname viene incorporado. Con ES Modules, Node.js utiliza un sistema basado en URLs y no incluye estos globales. Por eso, cuando intentas usar __dirname en un módulo ES, Node.js lanza la excepción porque esa variable no existe en ese ámbito.

Solución con import.meta.url y fileURLToPath: la forma recomendada de recrear __dirname en ES Modules es combinar import.meta.url con la utilidad fileURLToPath del módulo url de Node.js.

Implementación paso a paso en un módulo ES:

import { fileURLToPath } from url; import { dirname } from path; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); console.log(__dirname); console.log(__filename);

Cómo funciona: import.meta.url te da la URL del módulo ES actual. Luego, fileURLToPath convierte esa URL en una ruta local del sistema de archivos. Con dirname aplicado a __filename obtienes la carpeta del archivo, reproduciendo el comportamiento de __dirname en CommonJS. Así tu código se comporta casi igual que en un módulo CommonJS, pero manteniendo compatibilidad con ES Modules.

Cuándo usar este enfoque: cada vez que tu código trabaje con el sistema de archivos con fs para leer o escribir, necesite rutas relativas para activos estáticos o configuraciones, o se ejecute en el ámbito de ES Modules usando import y export en lugar de require.

Conclusión práctica: el error ReferenceError: __dirname is not defined in ES module scope puede desconcertar al migrar a ES Modules. Por fortuna, con import.meta.url y fileURLToPath puedes reintroducir fácilmente la funcionalidad familiar sin renunciar a las ventajas del estándar moderno.

En Q2BSTUDIO, empresa de desarrollo de software, construimos aplicaciones a medida y software a medida robusto y escalable con Node.js, TypeScript y arquitecturas cloud nativas. Si necesitas un partner técnico para acelerar tu roadmap digital, te ayudamos desde el diseño hasta la puesta en producción. Descubre nuestro enfoque en desarrollo de aplicaciones y software multiplataforma.

Además, desplegamos y operamos tus soluciones en entornos de alta disponibilidad con buenas prácticas DevSecOps, observabilidad y CI CD, apoyándonos en servicios cloud aws y azure. Si quieres optimizar costes, resiliencia y seguridad de tus cargas de trabajo, conoce nuestros servicios cloud en AWS y Azure.

Nuestro equipo es especialista en inteligencia artificial e ia para empresas, creación de agentes IA, ciberseguridad y pentesting, servicios inteligencia de negocio y analítica avanzada con power bi. Combinamos estas capacidades para que tus plataformas no solo funcionen, sino que aprendan, se protejan y generen valor continuo.

Palabras clave recomendadas para tu estrategia de posicionamiento: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat