nodejs的path模块

path路径模块

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

例如:

如果在js代码中,使用path模块来处理路径,需要先导入

const path=require('path')

常用的API

path.resolve拼接规范的绝对路径

path.sep获取操作系统的路径分隔符

path.parse解析路径并返回对象

path.basename获取路径的基础名称

path.dirname获取路径的目录名

path.extname获取路径的扩展名

path.join()方法

用来将多个路径片段拼接成一个完整的路径字符串

path.join的代码实例

path.join()方法,用来将多个路径片段拼接成一个完整的路径字符串

fs.readFile(path.join(__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’)代码会报错,因为多了一个.,应该是fs.readFile(path.join(__dirname+‘/files/1.txt’),就差一点就对了,当前足够细心的话这个问题也很容易定位到,当然通过更好的代码习惯去规避这些小问题肯定是更好的啦
在这里插入图片描述

path.basename()方法

用来从路径字符串中,将文件名解析出来。

语法格式

path.basename(path[, suffix])

path必选参数,表示一个路径的字符串

suffix可选参数,文件扩展名

返回路径中的最后一部分

path.basename()的代码实例

const path = require('path')

// 定义文件的存放路径
const fpath = 'a/b/c/index.txt'

var fullName = path.basename(fpath)
console.log(fullName)//输出index.html

var nameWithoutExt = path.basename(fpath, '.txt')
console.log(nameWithoutExt)//输出index

在这里插入图片描述

path.extname()

可以使用path.extname()方法获取路径中的扩展名部分

语法格式

path.extname(path)

path.extname()代码实例

const path = require('path')
const fpath = 'a/b/c/index.txt'

const fext = path.extname(fpath)
console.log(fext)

代码运行截图
在这里插入图片描述

综合案例-时钟案例

案例要实现的功能

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>index首页</title>
    <style>
        html,
        baby {
            margin: 0;
            padding: 0;
            height: 100%;
            background-image: linear-gradient(to bottom right, red, gold);
        }
 
        .box {
            width: 400px;
            height: 250px;
            background-color: rgba(255, 255, 255, 0.6);
            border-radius: 6px;
            position: absolute;
            left: 50%;
            top: 40%;
            transform: translate(-50%, -50%);
            box-shadow: 1px 1px 10px #fff;
            text-shadow: 0px 1px 30px white;
            display: flex;
            justify-content: space-around;
            align-items: center;
            font-size: 70px;
            user-select: none;
            padding: 0 20px;
 
            /*    盒子投影*/
            -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent),
            color-stop(0%, transparent), to(rgba(250, 250, 250, .2)));
        }
    </style>
</head>
<body>
<div class="box">
    <div id="HH">00</div>
    <div>:</div>
    <div id="mm">00</div>
    <div>:</div>
    <div id="ss">00</div>
</div>
<script>
    window.onload = function () {
        //    定时器,每隔1秒执行1次
        setInterval(() => {
            var dt = new Date()
            var HH = dt.getHours()
            var mm = dt.getMinutes()
            var ss = dt.getSeconds()
 
            //    为页面上的元素赋值
            document.querySelector('#HH').innerHTML = padZero(HH)
            document.querySelector('#mm').innerHTML = padZero(mm)
            document.querySelector('#ss').innerHTML = padZero(ss)
        }, 1000)
    }
 
    //    补零函数
    function padZero(n) {
        return n > 9 ? n : '0' + n
    }
</script>
</body>
</html>

将素材目录下的index.html页面,拆分成三个文件,分别是:

index.css

index.js

idex.html

并且将拆分出来的3个文件,存放到clock目录中

案例实现的步骤

  • 导入需要的模块,创建两个正则表达式,分别用来匹配

实现代码

// 1.1导入fs文件系统模块
const fs = require('fs')

// 1.2导入path路径处理模块
const path = require('path')

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

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

//  2.1调用fs.readFile() 方法读取文件
fs.readFile(path.join(__dirname, './素材/index.html'), 'utf8', function (err, dataStr) {
//  2.2读取HTML文件失败
    if (err) return console.log('读取HTML文件失败!' + err.message)
//  2.3读取文件成功后,调用对应的三个方法,分别拆解出css, js, html文件
    resolveCSS(dataStr)
    resolveJS(dataStr)
    resolveHtml(dataStr)
})

// 3.1 定义处理css样式的方法
function resolveCSS(htmlStr) {
//    3.2 使用正则提取需要的内容
    const r1 = regStyle.exec(htmlStr)
//    3.3 将提取出来的样式字符串,进行字符串的replace替换操作,去掉首位标签
    const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
//    3.4 调用fs.wirteFile()方法,将提取的样式,写入到clock目录中index.css的文件里面
    fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, function (err) {
        if (err) return console.log('写入css样式失败!' + err.message)
        console.log('写入样式文件成功!')
    })
}
 
// 4.1处理js脚本
function resolveJS(htmlStr) {
//4.2 通过正则,提取对于的<script></script> 标签内容
    const r2 = regScript.exec(htmlStr)
//    4.3将提取出来的内容,做进一步的处理
    const newJS = r2[0].replace('<script>', '').replace('</script>', '')
//    4.4将处理的结果,写入到clock目录中的index.js文件里面
    fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, function (err) {
        if (err) return console.log('写入JavaScri脚本失败!' + err.message)
        console.log('写入JS脚本成功!')
    })
}
 
//5.1定义处理HTML结构的方法
function resolveHtml(htmlStr) {
    //    5.2 将字符串调用replace方法,把内嵌的style和script标签,替换为外联的link和script标签
    const newHTML = htmlStr.replace(regStyle, '<link rel ="stylesheet" href="./index.css" />').replace(regScript, '<script src="./index.js"></script>')
    //    5.3 写入index.html 这个文件
    fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, function (err) {
        if (err) return console.log('写入HTML文件失败!' + err.message)
        console.log('写入HTML页面成功!')
    })
}


案例中的两个注意点

  • fs.write()方法只能用来创建文件,不能用来创建路径
    完成时钟案例运行代码运行失败,因为路径中没有clock文件夹,fs.write不能创建路径,所以导致写入文件失败。手动创建clock文件夹之后路径正确文件写入成功
    在这里插入图片描述

  • 重复调用fs.writeFile()写入同一个文件,新写入的内容会覆盖之前的旧的内容。
    在这里插入图片描述

重复执行node操作,依然会成功,新写入的内容会覆盖旧的内容。

猜你喜欢

转载自blog.csdn.net/weixin_55355282/article/details/131080220