【发布时间】:2020-09-01 21:03:00
【问题描述】:
如何获取当前模块的目录和文件名?在 Node.js 中,我会使用:__dirname & __filename
【问题讨论】:
如何获取当前模块的目录和文件名?在 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);
【讨论】:
https://deno.land/x/dirname 不存在,这是一个死链接。
/C:/path/to/file.json,readTextFile 无法理解。