path路徑模塊
1.path.join() 將多個(gè)路徑片段拼接成一個(gè)完整的路徑字符串
../可以抵消上一層路徑
凡是遇到路徑拼接都用path.join()方法,不再用+號(hào)拼接
2.path.basename() 從路徑字符串中次询,將文件名解析出來
解析最后一部分的文件名 如果傳一個(gè)參數(shù) 解析出最后一個(gè)的文件名
如果傳兩個(gè)參數(shù) 第二個(gè)參數(shù)則為最后一個(gè)片段的拓展名 得到最后一個(gè)除拓展名外的文件名
3.path.extname() 獲取路徑中的拓展名部分
4.關(guān)于正則補(bǔ)充
?\s 表示空白字符 \S表示非空白字符 *表示可以匹配任意次
匹配<style></style>標(biāo)簽的正則
?/<style>[\s\S]*<\/style>/匹配所有字符任意次
.exec() 該方法用于檢索字符串 (test也用于檢索 但返回值是true/false) 如果找到 返回值是一個(gè)數(shù)組校读,其中存放匹配的結(jié)果浴讯,此數(shù)組的第 0 個(gè)元素是與正則表達(dá)式相匹配的文本 如果未找到 返回值null
例題 簡(jiǎn)化HTML 將css/js 抽取再進(jìn)行標(biāo)簽嵌入
//把一份HTMl文件中的css js 做抽取存放
//先引入 path fs
//定義標(biāo)簽正則 ?方便檢索
const regCss = /<style>[\s\S]*<\/style>/
const regJs = /<script>[\s\S]*<\/script>/
//讀取HTML文件
fs.readFile(path.join(__dirname, './add.html'), 'utf8', function (err, dataStr) {
? ? if (err) {
? ? ? ? return console.log('讀取文件失敗' + err.message);
? ? }
? ? //調(diào)用方法
? ? getCss(dataStr);
? ? getJs(dataStr);
? ? getHtml(dataStr);
})
function getCss(htmlStr) {
? ? //如果檢索到 返回一個(gè)數(shù)組
? ? const r1 = regCss.exec(htmlStr)
? ? //索引為0的是提取的需要的內(nèi)容
? ? const newR1 = r1[0].replace("<style>", " ").replace("</style>", " ")
? ? fs.writeFile(path.join(__dirname, './clock/index.css'), newR1, function (err) {
? ? ? ? if (err) {
? ? ? ? ? ? return console.log('寫入失敗' + err.message);
? ? ? ? }
? ? ? ? console.log('寫入CSS成功');
? ? })
}
//將提取出來的數(shù)據(jù) 寫入到相應(yīng)的文件中
function getJs(htmlStr) {
? ? //如果檢索到 返回一個(gè)數(shù)組
? ? const r1 = regJs.exec(htmlStr)
? ? //索引為0的是提取的需要的內(nèi)容 ?將不需要的標(biāo)簽替換成" "空字符串
? ? const newR1 = r1[0].replace("<script>", " ").replace("</script>", " ")
? ? //將提取到的數(shù)據(jù) 寫入一個(gè)文件中
? ? fs.writeFile(path.join(__dirname, './clock/index.js'), newR1, function (err) {
? ? ? ? if (err) {
? ? ? ? ? ? return console.log('寫入失敗' + err.message);
? ? ? ? }
? ? ? ? console.log('寫入JS成功');
? ? })
}
//不需要多余的css樣式以及js的簡(jiǎn)化版HTML文件
function getHtml(htmlStr) {
? ? let newR1 = htmlStr.replace(regCss, '<link rel="stylesheet" href="./clock/index.css">').replace(regJs, '<script src="./clock/index.js"></script>')
? ? fs.writeFile(path.join(__dirname, './clock/index.html'), newR1, function (err) {
? ? ? ? if (err) {
? ? ? ? ? ? return console.log('寫入失敗' + err.message);
? ? ? ? }
? ? ? ? console.log('寫入html成功');
? ? })
}