Implementing __dirname in ES6 modules using import.meta.url

; Date: Sun Apr 08 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.

About the Author(s)

(davidherron.com) David Herron : David Herron is a writer and software engineer focusing on the wise use of technology. He is especially interested in clean energy technologies like solar power, wind power, and electric cars. David worked for nearly 30 years in Silicon Valley on software ranging from electronic mail systems, to video streaming, to the Java programming language, and has published several books on Node.js programming and electric vehicles.

Books by David Herron

(Sponsored)