Node.js' __dirname & __filename equivalent in Deno

In Deno, there aren't variables like __dirname or __filename but you can get the same values thanks to import.meta.url

You can use URL constructor for that:

const __filename = new URL('', import.meta.url).pathname;
// Will contain trailing slash
const __dirname = new URL('.', import.meta.url).pathname;

Note: On windows it will contain /, method shown below will work on windows


Also, you can use std/path

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));

Other alternative 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);

Tags:

Node.Js

Deno