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 @   槑孒  阅读(141)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
点击右上角即可分享
微信分享提示