Node.js' __dirname & __filename 在 Deno 中等效

Node.js' __dirname & __filename equivalent in Deno

如何获取当前模块的目录和文件名?.在 Node.js 中,我会使用:__dirname & __filename

在 Deno 中,没有像 __dirname or __filename but you can get the same values thanks to import.meta.url

这样的变量

您可以为此使用 URL 构造函数:

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

注意:在windows上它将包含/,下面显示的方法将适用于windows


此外,您可以使用 std/path

import * as path from "https://deno.land/std@0.57.0/path/mod.ts";

const __filename = path.fromFileUrl(import.meta.url);
// Without trailing slash
const __dirname = path.dirname(path.fromFileUrl(import.meta.url));

其他替代方法是使用第三方模块,例如:deno-dirname

import { __ } from 'https://deno.land/x/dirname/mod.ts';
const { __filename, __dirname } = __(import.meta);