nodejs在esm模式下获取当前文件路径

在 Windows 环境下使用 new URL(import.meta.url).pathname 时,前面多一个 / 是因为 URL 对象在处理文件路径时会按照 POSIX 标准格式化路径,而在 Windows 中,文件路径通常以盘符开头。

解释

  • import.meta.url 返回一个文件 URL,例如 file:///C:/path/to/file.js
  • new URL(import.meta.url).pathname 返回路径部分,这在 POSIX 系统中被认为是 /C:/path/to/file.js

解决方案

为了在 Windows 环境中正确处理路径,可以使用 Node.js 提供的 path 模块来处理路径,使其符合 Windows 的路径格式。

以下是一个处理方法的示例:

import { fileURLToPath } from 'url';
import path from 'path';

// Convert the file URL to a path
const __filename = fileURLToPath(import.meta.url);

// Get the directory name of the file
const __dirname = path.dirname(__filename);

console.log(__dirname);

详细步骤

  1. 使用 fileURLToPath

    • 将文件 URL 转换为路径。
  2. 使用 path.dirname

    • 获取文件的目录路径。

示例代码解释

import { fileURLToPath } from 'url';
import path from 'path';

// 将 import.meta.url 转换为文件路径
const __filename = fileURLToPath(import.meta.url);

// 获取文件所在的目录路径
const __dirname = path.dirname(__filename);

console.log(__dirname);
posted @ 2024-06-28 14:37  槑孒  阅读(13)  评论(0编辑  收藏  举报