Implementing __dirname in ES6 modules using import.meta.url

By: (plus.google.com) +David Herron; Date: April 8, 2018

Tags: Node.JS » JavaScript

ES6 modules are a nifty new way to write modules. In Node.js, our traditional CommonJS modules had several injected variables one of which, __dirname, was incredibly useful. None of those variables exist in ES6 modules. The Node.js team is working on replacements that work in ES6 module contexts, and a new feature has been added in Node.js 10.0.0-pre giving us a way forward to implement the __dirname variable in ES6 modules.

As of this writing, official release of Node.js 10 is still a couple weeks away. But one can clone the master Node.js repository and make your own build.

Last week I happened across a live-stream of an online meeting of Node.js core team developers to discuss Modules. I popped in a question about import.meta and learned the feature had been added to the master Node.js repository, and is slated for inclusion in Node.js 10.

If you want to play along with this right now, you'll need to clone the repository at (github.com) https://github.com/nodejs/node then build the source for your platform. Once Node.js 10 is released that will not be necessary.

Rationale for __dirname

Why is the __dirname variable important? Let's take two examples.

An Express application will routinely have this sort of code while wiring up the Application object:

...
import express from 'express';
import hbs from 'hbs';
...
const app = express();
...
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
hbs.registerPartials(path.join(__dirname, 'partials'));
...
app.use(express.static(path.join(__dirname, 'public')));
...
app.use('/assets/vendor/bootstrap/js', express.static( 
  path.join(__dirname, 'node_modules', 'bootstrap', 'dist', 'js'))); 
app.use('/assets/vendor/bootstrap/css', express.static( 
  path.join(__dirname, 'minty'))); 
app.use('/assets/vendor/jquery', express.static( 
  path.join(__dirname, 'node_modules', 'jquery'))); 
app.use('/assets/vendor/popper.js', express.static( 
  path.join(__dirname, 'node_modules', 'popper.js', 'dist')));  
app.use('/assets/vendor/feather-icons', express.static( 
  path.join(__dirname, 'node_modules', 'feather-icons', 'dist'))); 

That is, we need to incorporate files from the file-system. The files are located next to the JavaScript code being executed. The __dirname variable facilitates accessing those files.

We cannot use a pathname like ./views because the . directory can easily be extremely different from the location of the script being executed.

Similarly an Electron app might refer to local HTML files as so:

class CreateFileWindow extends electron.BrowserWindow {

    constructor(editorWindow) {
        super({
            height: 600,
            width: 800,
            frame: false,
            webPreferences: { backgroundThrottling: false }
        });
        this[_layout_file] = undefined;
        this[_editor_window] = editorWindow;

        this.loadURL(`file://${__dirname}/create-file-bootstrap.html`);
        // this.webContents.openDevTools();
    }
    ...
}

This is even clearer since I believe a file: URL must use a fully rooted pathname.

The problem: __dirname is not defined

The Express code shown above will fail because it is an ES6 module (using import statements) and __dirname does not exist. To see the failure in action let's try a small example.

$ node --version
v10.0.0-pre
$ cat ./test.mjs 

console.log(__dirname);

$ node --experimental-modules  ./test.mjs 
(node:20829) ExperimentalWarning: The ESM module loader is experimental.
ReferenceError: __dirname is not defined
    at file:///Volumes/Extra/book-4th/chap07/notes/test.mjs:3:13
    at ModuleJob.run (internal/modules/esm/ModuleJob.js:106:14)
    at <anonymous>

The --experimental-modules flag is required to turn on the ES6 module support. As you can see, the expected error is thrown, __dirname is not defined.

Solution, import.meta

To start to see the solution, let's make this change:

$ node --version
v10.0.0-pre
$ cat test.mjs 

console.log(JSON.stringify(import.meta));

console.log(__dirname);

$ node --experimental-modules  ./test.mjs 
(node:20909) ExperimentalWarning: The ESM module loader is experimental.
{"url":"file:///Volumes/Extra/book-4th/chap07/notes/test.mjs"}
ReferenceError: __dirname is not defined
    at file:///Volumes/Extra/book-4th/chap07/notes/test.mjs:4:13
    at ModuleJob.run (internal/modules/esm/module_job.js:106:14)

We added a line to demonstrate that import.meta exists in Node.js 10, and that it includes a field named url containing the file: URL corresponding to the currently executing file.

Then with a little bit of work we can implement __dirname with this addition to test.mjs:

import path from 'path';

console.log(JSON.stringify(import.meta));

const moduleURL = new URL(import.meta.url);
console.log(`pathname ${moduleURL.pathname}`);
console.log(`dirname ${path.dirname(moduleURL.pathname)}`);

const __dirname = path.dirname(moduleURL.pathname);

console.log(__dirname);

This has excess code so we can see each step.

When executed we get this:

$ node --experimental-modules  ./test.mjs 
(node:21264) ExperimentalWarning: The ESM module loader is experimental.
{"url":"file:///Volumes/Extra/book-4th/chap07/notes/test.mjs"}
pathname /Volumes/Extra/book-4th/chap07/notes/test.mjs
dirname /Volumes/Extra/book-4th/chap07/notes
/Volumes/Extra/book-4th/chap07/notes

Minimalized code would be:

import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);

When executed we get this:

$ node --experimental-modules  ./test2.mjs 
(node:21339) ExperimentalWarning: The ESM module loader is experimental.
/Volumes/Extra/book-4th/chap07/notes

In other words, we take the pathname from the URL corresponding to the currently executing file, then use path.dirname to get the enclosing directory.

As it stands every module requiring the __dirname variable needs those two lines of code.

« Fix NVM_NODEJS_ORG_MIRROR deprecation warning when running npm install Can I monkey patch a Node.js module installed from the npm repository so the patch is maintained after npm install? »
2016 Election 2018 Elections Acer C720 Ad block Air Filters Air Quality Air Quality Monitoring AkashaCMS Amazon Amazon Kindle Amazon Web Services America Amiga and Jon Pertwee Android Anti-Fascism AntiVirus Software Apple Apple Hardware History Apple iPhone Apple iPhone Hardware April 1st Arduino ARM Compilation Artificial Intelligence Astronomy Astrophotography Asynchronous Programming Authoritarianism Automated Social Posting AWS DynamoDB AWS Lambda Ayo.JS Bells Law Big Brother Big Data Big Finish Big Science Bitcoin Mining Black Holes Blade Runner Blockchain Blogger Blogging Books Botnets Cassette Tapes Cellphones China China Manufacturing Christopher Eccleston Chrome Chrome Apps Chromebook Chromebox ChromeOS CIA CitiCards Citizen Journalism Civil Liberties Climate Change Clinton Cluster Computing Command Line Tools Comment Systems Computer Accessories Computer Hardware Computer Repair Computers Conservatives Cross Compilation Crouton Cryptocurrency Curiosity Rover Currencies Cyber Security Cybermen Cybersecurity Daleks Darth Vader Data backup Data Formats Data Storage Database Database Backup Databases David Tenant DDoS Botnet Department of Defense Department of Justice Detect Adblocker Developers Editors Digital Nomad Digital Photography Diskless Booting Disqus DIY DIY Repair DNP3 Do it yourself Docker Docker MAMP Docker Swarm Doctor Who Doctor Who Paradox Doctor Who Review Drobo Drupal Drupal Themes DVD E-Books E-Readers Early Computers eGPU Election Hacks Electric Bicycles Electric Vehicles Electron Eliminating Jobs for Human Emdebian Encabulators Energy Efficiency Enterprise Node EPUB ESP8266 Ethical Curation Eurovision Event Driven Asynchronous Express Face Recognition Facebook Fake News Fedora VirtualBox Fifth Doctor File transfer without iTunes FireFly Flash Flickr Fraud Freedom of Speech Front-end Development G Suite Gallifrey git Github GitKraken Gitlab GMAIL Google Google Chrome Google Gnome Google+ Government Spying Great Britain Green Transportation Hate Speech Heat Loss Hibernate High Technology Hoax Science Home Automation HTTP Security HTTPS Human ID I2C Protocol Image Analysis Image Conversion Image Processing ImageMagick In-memory Computing InfluxDB Infrared Thermometers Insulation Internet Internet Advertising Internet Law Internet of Things Internet Policy Internet Privacy iOS Devices iPad iPhone iPhone hacking Iron Man iShowU Audio Capture iTunes Janet Fielding Java JavaFX JavaScript JavaScript Injection JDBC John Simms Journalism Joyent Kaspersky Labs Kext Kindle Kindle Marketplace Large Hadron Collider Lets Encrypt LibreOffice Linux Linux Hints Linux Single Board Computers Logging Mac Mini Mac OS Mac OS X Machine Learning Machine Readable ID Macintosh macOS macOS High Sierra macOS Kext MacOS X setup Make Money Online March For Our Lives MariaDB Mars Mass Violence Matt Lucas MEADS Anti-Missile Mercurial MERN Stack Michele Gomez Micro Apartments Microsoft Military AI Military Hardware Minification Minimized CSS Minimized HTML Minimized JavaScript Missy Mobile Applications Mobile Computers MODBUS Mondas Monetary System MongoDB Mongoose Monty Python MQTT Music Player Music Streaming MySQL NanoPi Nardole NASA Net Neutrality Network Attached Storage Node Web Development Node.js Node.js Database Node.js Performance Node.js Testing Node.JS Web Development Node.x North Korea npm NVIDIA NY Times Online advertising Online Community Online Fraud Online Journalism Online Photography Online Video Open Media Vault Open Source Open Source and Patents Open Source Governance Open Source Licenses Open Source Software OpenAPI OpenJDK OpenVPN Palmtop PDA Patrick Troughton PayPal Paywalls Personal Flight Peter Capaldi Peter Davison Phishing Photography PHP Plex Plex Media Server Political Protest Politics Postal Service Power Control President Trump Privacy Production use Public Violence Raspberry Pi Raspberry Pi 3 Raspberry Pi Zero ReactJS Recaptcha Recycling Refurbished Computers Remote Desktop Removable Storage Republicans Retro Computing Retro-Technology Reviews RFID Rich Internet Applications Right to Repair River Song Robotics Robots Rocket Ships RSS News Readers rsync Russia Russia Troll Factory Russian Hacking Rust SCADA Scheme Science Fiction SD Cards Search Engine Ranking Season 1 Season 10 Season 11 Security Security Cameras Server-side JavaScript Serverless Framework Servers Shell Scripts Silence Simsimi Skype SmugMug Social Media Social Media Networks Social Media Warfare Social Network Management Social Networks Software Development Software Patents Space Flight Space Ship Reuse Space Ships SpaceX Spear Phishing Spring Spring Boot Spy Satellites SQLite3 SSD Drives SSD upgrade SSH SSH Key SSL Stand For Truth Strange Parts Swagger Synchronizing Files Tegan Jovanka Telescopes Terrorism The Cybermen The Daleks The Master Time-Series Database Tom Baker Torchwood Total Information Awareness Trump Trump Administration Trump Campaign Twitter Ubuntu Udemy UDOO US Department of Defense Virtual Private Networks VirtualBox VLC VNC VOIP Vue.js Walmart Weapons Systems Web Applications Web Developer Resources Web Development Web Development Tools Web Marketing Webpack Website Advertising Weeping Angels WhatsApp William Hartnell Window Insulation Windows Windows Alternatives Wordpress World Wide Web Yahoo YouTube YouTube Monetization