ESM中的__dirname ?; ?__filename
console.log(import.meta.url);
// 运行会得到一个基于 file 协议的 URL:file:///D:/%E5%AD%A6%E4%B9%A0%E6%9D%82%E4%B8%83%E6%9D%82%E5%85%AB/ffPra/demo2/require.js
import { fileURLToPath } from "node:url";
console.log(fileURLToPath(import.meta.url));
//D:\学习杂七杂八\ffPra\demo2\require.js
__filename;?__dirname?
通过import.meta.url和fileURLToPath我们很容易得到__filename API;
import { dirname } from "node:path";
const __filename = fileURLToPath(import.meta.url);
//我们已经拿到了__filename的值,实现__dirname,借助Node.js的内部模块path的dirname方法实现;
const __dirname = dirname(__filename);
console.log(__dirname);
//D:\学习杂七杂八\ffPra\demo2
basename?获取当前文件
import { basename } from "node:path";
const __basename = basename(__filename);
console.log("__basename:", __basename);
//__basename: require.js
//join 拼接文件路径
import { join } from "node:path";
const newPath = join(__dirname, "new.js");
console.log(newPath);
//D:\学习杂七杂八\ffPra\demo2\new.js