如何获取当前模块的目录和文件名?在 Node.js 中,我会使用:__dirname&__filename为此
Mar*_*nde 19
在 Deno 中,没有像__dirnameor这样的变量,__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;
Run Code Online (Sandbox Code Playgroud)
注意:在 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));
Run Code Online (Sandbox Code Playgroud)
其他替代方法是使用第三方模块,例如: deno-dirname
import { __ } from 'https://deno.land/x/dirname/mod.ts';
const { __filename, __dirname } = __(import.meta);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2996 次 |
| 最近记录: |