esm中使用__dirname与__filename

ESM中的__dirname  ;  __filename

  1. import.meta.url
    import.meta 包含当前模块的一些信息,其中 import.meta.url 表示当前模块的 file: 绝对路径,拿到这个绝对路径我们就可以配合其他 API 来实现 __filename 和 __dirname。
    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
  2. fileURLToPath
    接下来需要把 file 协议转换成路径,我们需要借助 Node.js 内部 url 模块的 fileURLToPath API。
    import { fileURLToPath } from "node:url";console.log(fileURLToPath(import.meta.url));
    //D:\学习杂七杂八\ffPra\demo2\require.js
  3. __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

  4. basename 获取当前文件

    import { basename } from "node:path";const __basename = basename(__filename);
    console.log("__basename:", __basename);
    //__basename: require.js
  5. //join 拼接文件路径

    import { join } from "node:path";
    const newPath = join(__dirname, "new.js");
    console.log(newPath);
    //D:\学习杂七杂八\ffPra\demo2\new.js