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 页面成功!')
})
}