How can I get the directory & file name of the current module?. In Node.js I would use: __dirname
& __filename
for that
Since Deno 1.40 you can now use import.meta.dirname
and import.meta.filename
. Here's what the various import.meta
properties look like when running deno main.js
:
import.meta.dirname
: /home/foo/app
import.meta.filename
: /home/foo/app/main.js
import.meta.url
: file:///home/foo/app/main.js
Note that import.meta.url
is a browser standard, while the other two are server-side additions.
OLD ANSWER
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.