Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js' __dirname & __filename equivalent in Deno

Tags:

node.js

deno

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

like image 533
Marcos Casagrande Avatar asked May 15 '20 22:05

Marcos Casagrande


1 Answers

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);
like image 139
Marcos Casagrande Avatar answered Sep 28 '22 04:09

Marcos Casagrande