path的API使用

1.path方法

// join 方法,路径拼接
// 输出:E:\QQPCmgr\Desktop\Android_learn\node_test\files\1.txt
const path = require('path')
const textPath = path.join(__dirname,'./files/1.txt')
console.log(textPath)

// path.basename返回路径的最后一部分,即文件名,第二个参数可以删除后缀
const textName = path.basename(textPath,'.txt')
console.log(textName)
// 输出:1

// path.extname返回文件扩展名,返回.txt
console.log(path.extname(textPath))

2.练习(把html文件的js,html,css分别放到不同的文件夹)

const { error } = require('console')
const fs = require('fs')
const path =require('path')

// 1.3 定义正则表达式,分别匹配 <style></style> 和 <script></script> 标签
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/

fs.readFile(path.join(__dirname,'素材/day1/素材/index.html'),'utf-8',(error,dataStr)=>{
    if(error){
        console.log('读取文件失败'+ error.message)

    }
    resolveCSS(dataStr)
    resolveJS(dataStr)
    resolveHTML(dataStr)
})

function resolveCSS(htmlStr){
    // 使用正则提取需要的内容,返回一个字符串
 
    const r1 = regStyle.exec(htmlStr)
    const newCSS = r1[0].replace('<style>',' ').replace('</style>',' ')
    fs.writeFile(path.join(__dirname,'/素材/day1/素材/resolve.css'),newCSS,(error)=>{
        if(error){
            console.log('写入失败')
        }
    })

}

function resolveJS(htmlStr){
    // 使用正则提取需要的内容,返回一个数组
 
    const r1 = regScript.exec(htmlStr)
    const newCSS = r1[0].replace('<script>',' ').replace('</script>',' ')
    fs.writeFile(path.join(__dirname,'/素材/day1/素材/resolve.js'),newCSS,(error)=>{
        if(error){
            console.log('写入失败')
        }
    })

}
// 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, '/素材/day1/素材/resolve.html'), newHTML, function(err) {
      if (err) return console.log('写入 HTML 文件失败!' + err.message)
      console.log('写入 HTML 页面成功!')
    })
  }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值