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);
详细步骤
-
使用
fileURLToPath
:- 将文件 URL 转换为路径。
-
使用
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);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!