Node.js' __dirname & __filename equivalent in Deno
Asked Answered
D

2

39

How can I get the directory & file name of the current module?. In Node.js I would use: __dirname & __filename for that

Dygert answered 15/5, 2020 at 22:30 Comment(0)
D
52

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.

Dygert answered 15/5, 2020 at 22:30 Comment(3)
This didn't work for me on Windows, I found a working solution here: morioh.com/p/68bf0c73b2bbAlanna
Not working on Windows either - it generates paths with an incorrect leading space like /C:/path/to/file.json which readTextFile cannot understand.Pires
@AndrewKoster At least now it works.Jaquez
C
3

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));
Centrepiece answered 20/11, 2023 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.