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
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/[email protected]/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.
/C:/path/to/file.json
which readTextFile
cannot understand. –
Pires This is the up-to-date fix that just works
on all platforms as far as I can tell and provides complete feature parity:
import * as path from "https://deno.land/[email protected]/path/mod.ts";
const __filename = path.fromFileUrl(import.meta.url);
const __dirname = path.dirname(path.fromFileUrl(import.meta.url));
© 2022 - 2024 — McMap. All rights reserved.