如何获取当前模块的目录和文件名?在 Node.js 中,我会使用:__dirname
& __filename
为了那个原因
最佳答案
在 Deno 中,没有像 __dirname
这样的变量。或 __filename
但是由于 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);
关于Deno 中的 Node.js 的 __dirname 和 __filename 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61829367/