How can I get the directory & file name of the current module?. In Node.js I would use: __dirname
& __filename
for that
Asked
Active
Viewed 9,754 times
35

Carson
- 6,105
- 2
- 37
- 45

Marcos Casagrande
- 37,983
- 8
- 84
- 98
1 Answers
46
In Deno, there aren't variables like __dirname
or __filename
but you can get the same values thanks to import.meta.url
On *nix (including MacOS), you can use URL
constructor for that (won't work for Windows, see next option):
const __filename = new URL('', import.meta.url).pathname;
// Will contain trailing slash
const __dirname = new URL('.', import.meta.url).pathname;
Note: On Windows __filename
would be something like /C:/example/mod.ts
and __dirname
would be /C:/example/
. But the next alternative below will work on Windows.
Alternatively, you can use std/path
, which works on *nix and also Windows:
import * as path from "https://deno.land/std@0.188.0/path/mod.ts";
const __filename = path.fromFileUrl(import.meta.url);
// Without trailing slash
const __dirname = path.dirname(path.fromFileUrl(import.meta.url));
With that, even on Windows you get standard Windows paths (like C:\example\mod.ts
and C:\example
).
Another alternative for *nix (not Windows) is to use a third party module such as deno-dirname
:
import __ from 'https://deno.land/x/dirname/mod.ts';
const { __filename, __dirname } = __(import.meta);
But this also provides incorrect paths on Windows.

Marcos Casagrande
- 37,983
- 8
- 84
- 98
-
1This didn't work for me on Windows, I found a working solution here: https://morioh.com/p/68bf0c73b2bb – hb20007 Dec 25 '20 at 19:13
-
Not working on Windows either - it generates paths with an incorrect leading space like `/C:/path/to/file.json` which `readTextFile` cannot understand. – Marc Oct 08 '21 at 09:58
-
1@AndrewKoster At least now it works. – MEMark Dec 11 '21 at 21:33