浅析node的path路径模块

javascriptjavascript 2023-08-28 19:22:12 1145
摘要: path模块是nodejs中用于处理文件/目录路径的一个内置模块,可以看作是一个工具箱,提供诸多方法供我们使用,当然都是和路径处理有关的。同时在前端开发中path模块出现的频率也是比较高的,比如配置webpack的时候等。...

path 模块是 nodejs 中用于处理文件/目录路径的一个内置模块,可以看作是一个工具箱,提供诸多方法供我们使用,当然都是和路径处理有关的。同时在前端开发中 path 模块出现的频率也是比较高的,比如配置 webpack 的时候等。本文就来聊聊node的path路径模块。

node的path模块

1.path路径模块初认识

2.path模块的API

2.1 path.join()

语法格式为
在这里插入图片描述

需要注意的是这个返回的值为string

//引入path模块
const path=require("path")
//书写要拼接的路径
const pathStr=path.join('/a','/b/c','../','./d','e')

console.log(pathStr)

在这里插入图片描述

2.2 path.basename()

语法格式
在这里插入图片描述

  • path 必选参数,表示一个路径的字符串
  • 可选参数,表示文件扩展名
  • 表示路径中的最后一部分
const path=require("path")

const  fpath='./a/b/c/index.html'

var fullname=path.basename(fpath)

console.log(fullname)
//获取指定后缀的文件名
const namepath=path.basename(fpath,'.html')

console.log(namepath)

在这里插入图片描述

2.3 path.extname()

格式为
在这里插入图片描述

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

  • 返回: 返回得到的扩展名字符串

const path=require("path")

const fpath='./a/b/c/d/index.html'

const ftext =path.extname(fpath)

console.log(ftext)

在这里插入图片描述

3.时钟案例实践

源代码
点击右键查看源代码

3.1实现步骤

3.1.1步骤1 - 导入需要的模块并创建正则表达式

const path=require('path')
const fs=require('fs')

const regStyle=/<style>[\s\S]*<\/style>/

const scriptruler=/<script>[\s\S]*<\/script>/
//需要读取的文件
fs.readFile(path.join(__dirname,'/static/index.html'),'utf-8',function(err,dateStr){
    if(err){
        return console.log("读取失败")
    }
   resolveCSS(dateStr)
   resolveHTML(dateStr)
   resolveJS (dateStr)
})

3.1.2 自定义 resolveCSS resolveHTML resolveJS 方法

function resolveCSS(htmlStr){
    const r1=regStyle.exec(htmlStr)
    const newcss=r1[0].replace('<style>','').replace('</style>','')
    //将匹配的css写入到指定的index.css文件中
    fs.writeFile(path.join(__dirname,'/static/index.css'),newcss,function(err){
        if(err) return console.log("导入失败"+err.message)
        console.log("ojbk")
    })
}
function resolveJS(htmlStr){
    const r2=scriptruler.exec(htmlStr)
    const newcss=r2[0].replace('<script>','').replace('</script>','')
    //将匹配的css写入到指定的index.js文件中
    fs.writeFile(path.join(__dirname,'/static/index.js'),newcss,function(err){
        if(err) return console.log("导入失败"+err.message)
        console.log("ojbk")
    })
}
function  resolveHTML(htmlStr){
    const newhtml=htmlStr
    .replace(regStyle,'<link rel="stylesheet" href="./index.css">')
    .replace(scriptruler,'<script src="./index.js"></script>')
    //将匹配的css写入到指定的index.html文件中
    fs.writeFile(path.join(__dirname,'/static/index2.html'),newhtml,function(err){
        if(err) return console.log("导入失败"+err.message)
        console.log("ojbk")
    })
}

最终的结果就是在指定的文件中将样式剥离开

在这里插入图片描述

更多node相关知识,请访问:nodejs 教程!