nodejs学习笔记-03path路径模块

119 阅读3分钟

path路径模块

1.什么是path路径模块

path模块是Node.js官方提供的,用来处理路径的模块.它提供了一系列的方法和属性,用来满足用户对路径的处理需求

例如:

  • path.join()方法,用来将多个路径片段拼接成一个完整的路径字符串
  • path.basename()方法,用来从路径字符串中,将文件名解析出来

如果要在js文件当中,使用path模块来处理路径,则需要先导入它

const path = require('path')

2.如何实现路径的拼接,path.join()方法的使用

语法格式

path.join([...paths])

如下代码示例:我们可以看看使用path.join()方法处理后的路径

// path.join()方法的使用
const path = require('path')

// 注意:../会抵消前面的路径(如下例子,c被../抵消了)
const pathStr1 = path.join('/a','/b/c','../','./d','e')
console.log('pathStr1: ',pathStr1) // 输出: \a\b\d\e

const pathStr2 = path.join('/a','/b/c','../../','./d','e')
console.log('pathStr2: ',pathStr2) // 输出: \a\d\e   (两个../ 会抵消两层路径)

const pathStr3 = path.join(__dirname+'./files/1.txt')
console.log('pathStr3: ',pathStr3) // 输出: E:\02-learn\nodejs.\files\1.txt

读取文件代码示例

const path = require("path");
const fs = require("fs");

// 使用字符串拼接路径读取文件
fs.readFile(__dirname + "./files/1.txt", "utf8", function (err, dataStr) {
  if (err) {
    return console.log("文件读取失败" + err.message);
  }
  console.log("文件读取成功" + dataStr);
});
// 使用path.join()拼接路径读取文件
fs.readFile(
  path.join(__dirname, "./files/1.txt"),
  "utf8",
  function (err, dataStr) {
    if (err) {
      return console.log("文件读取失败" + err.message);
    }
    console.log("文件读取成功" + dataStr);
  }
);

上述代码运行结果

image.png 总结: 以拼接字符串形式写的文件路径,读取文件时读取失败,而使用path.join()方法读取文件读取成功,是因为 path.join()方法会帮我们屏蔽掉路径./files/1.txt中最前面的.

因此今后涉及到路径拼接的操作,应该更多地使用path.join()方法进行处理,避免直接使用 + 进行字符串的拼接

3.如何获取路径中的文件名,path.basename()方法的使用

使用path.basename()方法,可以获取路径中的最后一部分,通常用来获取路径中的文件名

语法格式

path.basename(path[,ext])
  • 参数1: path <string> 必选参数 ,表示一个路径的字符串
  • 参数2: ext <string>可选参数,表示文件的扩展名
  • 返回值: <string>表示路径中的最后一部分

示例代码:

const path = require("path");

// 定义文件的存放路径
const fpath = "a/b/c/index.html";

const fileName = path.basename(fpath);
console.log("fileName: ", fileName); // index.html

const fileNameWithoutExt = path.basename(fpath, ".html");
console.log("fileNameWithoutExt: ", fileNameWithoutExt); // index

4.如何获取路径中的文件扩展名, path.extname()方法的使用

语法格式

path.extname(path) // path为必选参数,表示一个路径的字符串

示例代码

const path = require("path");

// 定义文件的存放路径
const fpath = "a/b/c/index.html";

const fileExtName = path.extname(fpath);
console.log("fileExtName: ", fileExtName); // .html

path路径模块-fs文件读写操作-综合案例

1.案例需要实现的功能

给出一个完整的页面index.html文件,该文件中整合了html,css,js代码,现需要将index.html页面,拆分成三个文件:

  • index.css
  • index.js
  • index.html

并且将拆分出来的三个文件 ,存放在result目录下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    body,
    html {
        height: 100%;
        margin: 0;
        padding: 0;
        background: linear-gradient(to bottom, rgba(0, 255, 195, 0.514), rgba(0, 255, 234, 0.525))
    }

    #box {
        width: 400px;
        height: 200px;
        margin: 30px auto;
        text-align: center;
        line-height: 200px;
        background-color: pink;
        border: 2px solid #fff;
    }
</style>
<body>
    <div id="box">
        <span>path-fs-综合练习</span>
        <button id="button">点击打印当前时间</button>
    </div>
    <script>
        console.log('这是一段js的代码')
        const button = document.getElementById('button')
        button.onclick = function () {
            console.log('当前时间', new Date())
        }
    </script>
</body>

</html>

2.分析实现步骤

  1. 创建两个匹配<script>和<style>标签的正则表达式
  2. 使用fs模块,读取素材目录中需要被处理的index.html文件
  3. 自定义resolveCss方法,来写入index.css样式文件
  4. 自定义resolveJs方法,来写入index.js样式文件
  5. 自定义resolveHtml方法,来写入index.html样式文件

3.具体实现代码

3.1写正则表达式

// 其中 \s表示空白字符,   \S表示非空白字符   , *表示匹配任意次
// 匹配<style></style>标签的正则
const RegStyle = /<style>[\s\S]*<\/style>/

// 匹配<script></script>标签的正则
const RegScript = /<script>[\s\S]*<\/script>/

3.2创建 path-fs综合.js文件写入代码

//引入模块
const path = require("path");
const fs = require("fs");
// 定义正则
const regStyle = /<style>[\s\S]*<\/style>/;
const regScript = /<script>[\s\S]*<\/script>/;
// 读取素材案例 index.html文件
fs.readFile(
  path.join(__dirname, "/index.html"),
  "utf8",
  function (err, dataStr) {
    if (err) {
      return console.log("文件读取失败" + err.message);
    }
    console.log("文件读取成功" + dataStr);
    // 依次调用写好的resolveCss,resolveJs,resolveHtml方法
    resolveCss(dataStr);
    resolveJs(dataStr);
    resolveHtml(dataStr);
  }
);
// 定义resolveCss方法,处理css样式部分
/* 注意:正则的exec()方法 用于检索字符串中的正则表达式匹配,
返回一个数组,其中存放匹配的结果,若未存在匹配,则返回null */
function resolveCss(htmlStr) {
  // 通过正则提取对应的<style></style>标签内容
  const r1 = regStyle.exec(htmlStr);
  // 利用replace方法将提取出来的内容 去掉style标签
  const newCss = r1[0].replace("<style>", "").replace("</style>", "");
  // 写入index.css文件
  fs.writeFile(
    path.join(__dirname, "/result/index.css"),
    newCss,
    function (err) {
      if (err) {
        return console.log("写入css文件失败" + err.message);
      }
      console.log("css文件写入成功");
    }
  );
}
// 定义resolveJs方法,处理js部分代码
function resolveJs(htmlStr) {
  // 通过正则提取对应的<script></script>标签内容
  const r2 = regScript.exec(htmlStr);
  // 利用replace方法将提取出来的内容 去掉script标签
  const newJs = r2[0].replace("<script>", "").replace("</script>", "");
  // 写入index.js文件
  fs.writeFile(path.join(__dirname, "/result/index.js"), newJs, function (err) {
    if (err) {
      return console.log("js文件写入失败" + err.message);
    }
    console.log("js文件写入成功");
  });
}
// 定义resolveHtml方法,处理html结构
function resolveHtml(htmlStr) {
  // 将字符串调用replace方法,把页面中style标签和script标签,替换为外联的link,和script标签
  const newHtml = htmlStr
    .replace(regStyle, '<link rel="stylesheet" href="./index.css">')
    .replace(regScript, '<script src="./index.js"></script>');
  // 写入index.html文件
  fs.writeFile(
    path.join(__dirname, "/result/index.html"),
    newHtml,
    function (err) {
      if (err) {
        return console.log("html文件写入失败" + err.message);
      }
      console.log("html文件写入成功");
    }
  );
}

注意:

  1. result目录需要手动创建,fs.writeFile()方法只能用来创建文件,不会创建路径
  2. 重复写入同一个文件时,新的内容会覆盖之前的内容