1 fileURLToPath 结合 import.meta.url
fileURLToPath Added in: v10.12.0 import.meta.url Added in: v10
ts
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
2. import.meta.dirname
✔️
Added in: v21.2.0, v20.11.0
最少依赖最推荐写法。
ts
const __dirname = import.meta.dirname
- 冷知识 1:
import
虽然不能在 cjs 中使用,但是import.meta
可以 - 冷知识 2:Node.js 的 LTS 已经是 v22 了,v18 还有三周就要过保了,v20 也只有一年保质期了。LTS 意味着稳定和安全,大家踊跃升级呀。
当前时间数据:2025-4-10
Release | Security Support | Latest |
---|---|---|
23 | Ends in 1 month and 3 weeks(01 Jun 2025) | 23.11.0(01 Apr 2025) |
22 (LTS) | Ends in 2 years(30 Apr 2027) | 22.14.0(11 Feb 2025) |
20 (LTS) | Ends in 1 year(30 Apr 2026) | 20.19.0(13 Mar 2025) |
18 (LTS) | Ends in 3 weeks(30 Apr 2025) |
18.20.8(27 Mar 2025) |
可以看下 import.meta 里面还有哪些值
ts
console.log('process.versions:', process.versions.node);
console.log(import.meta);
ts
❯ node import.meta.js
process.versions: 22.7.0
[Object: null prototype] {
dirname: 'F:\\temp',
filename: 'F:\\temp\\import.meta.js',
resolve: [Function: resolve],
url: 'file:///F:/temp/import.meta.js'
}
3. new URL 结合 import.meta.url
只能在非 Windows 操作系统中用。Macos 系统未尝试大家可以帮忙试试。
ts
import path from 'path'
const __dirname = path.dirname(new URL(import.meta.url).pathname)
Windows 下返回 __dirname: /F:/temp
正确应该是 F:\\temp