自学内容网 自学内容网

path.resolve、path.join

node中的path 模块:用于处理文件和目录的路径的实用工具;经常在一些打包配置中出现

一、path.resolve

  • __dirname属于常量,案例中为D:\2024\webpack\webpack-demo\src
  • __dirname只能写在最前面,会覆盖之前的所有路径
  • / 根目录也会覆盖之前的所有路径,直接变成以他为开始
  • path.resolve()相当于path.resolve(__dirname),__dirname默认都会在第一个位置
// 可以在文件里写入,点击该文件所在文件夹选终端打开,node ./index.js,启动测试代码
console.log("node path", path.resolve());
console.log("node path", path.resolve(__dirname));
console.log("node path", path.resolve(__dirname, ""));
console.log("node path", path.resolve(__dirname, "./"));
console.log("node path", path.resolve(__dirname, "../"));
console.log("node path", path.resolve(__dirname, "/"));
console.log("node path", path.resolve(__dirname, "a", "/b"));
console.log("node path", path.resolve(__dirname, "a", "/b", __dirname));

// 结果
node path D:\2024\webpack\webpack-demo\src
node path D:\2024\webpack\webpack-demo\src
node path D:\2024\webpack\webpack-demo\src
node path D:\2024\webpack\webpack-demo\src
node path D:\2024\webpack\webpack-demo
node path D:\
node path D:\b
node path D:\2024\webpack\webpack-demo\src

二、path.join

  • 默认调用得到一个点.
  • 首位是相对路径就不会有点, 首位是cd …/会保持原样…\,首位是/保持不变\
  • 从实际拼接效果上看:a === ./a === /a
  • 其他情况为路径拼接,得到一个相对路径值
console.log("node path", path.join());
console.log("node path", path.join("a", "/b"));
console.log("node path", path.join("/a", "/b"));
console.log("node path", path.join("./a", "./b"));
console.log("node path", path.join("../a", "/b"));
console.log("node path", path.join("../a", "../b"));

// 结果
node path .
node path a\b
node path \a\b
node path a\b
node path ..\a\b
node path ..\b
  • path.join只会帮助拼接,__dirname这种绝对路径常量,如果必要只能一般写第一个,否则会得到奇怪路径;
console.log("node path", path.join(__dirname, "./a", "/b"));
console.log("node path", path.join("./a", __dirname, "/b"));
console.log("node path", path.join("/", __dirname, "/b"));
console.log("node path", path.join("./", __dirname, "/b"));
console.log("node path", path.join(".", __dirname, "/b"));
console.log("node path", path.join("", __dirname, "/b"));

// 结果
node path D:\2024\webpack\webpack-demo\src\a\b
node path a\D:\2024\webpack\webpack-demo\src\b
node path \D:\2024\webpack\webpack-demo\src\b
node path D:\2024\webpack\webpack-demo\src\b
node path D:\2024\webpack\webpack-demo\src\b
node path D:\2024\webpack\webpack-demo\src\b

原文地址:https://blog.csdn.net/hole_diss/article/details/143956327

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!