path 模塊是 nodejs 中用于處理文件/目錄路徑的一個內置模塊,可以看作是一個工具箱,提供諸多方法供我們使用,當然都是和路徑處理有關的。同時在前端開發中 path 模塊出現的頻率也是比較高的,比如配置 webpack 的時候等。本文就來聊聊node的path路徑模塊。
path 模塊是 Node.js 官方提供的、用來處理路徑的模塊。它提供了一系列的方法和屬性,用來滿足用戶對路徑的處理需求。
(資料圖)
path.join() 方法,用來將多個路徑片段拼接成一個完整的路徑字符串
語法格式為
…paths(string) 路徑片段的序列 ,就是你需要拼接的所有路徑系列。【相關教程推薦:nodejs視頻教程、編程教學】
需要注意的是這個返回的值為string
//引入path模塊const path=require("path")//書寫要拼接的路徑const pathStr=path.join("/a","/b/c","../","./d","e")console.log(pathStr)
使用 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)
path.extname()用于獲取路徑中的文件擴展名
格式為
path 必選參數,表示一個路徑的字符串
返回: 返回得到的擴展名字符串
const path=require("path")const fpath="./a/b/c/d/index.html"const ftext =path.extname(fpath)console.log(ftext)
將所提供的代碼(一個文件同時擁有html,css,js)進行拆分 拆分成三個文件分別為index.html index.css index.js并將其存放到一個準備好的文件中
源代碼點擊右鍵查看源代碼
1.創建兩個正則表達式,分別用來匹配 <style>
和 <script>
標簽 2. 使用 fs 模塊,讀取需要被處理的 HTML 文件 3. 自定義 resolveCSS 方法,來寫入 index.css 樣式文件 4. 自定義 resolveJS 方法,來寫入 index.js 腳本文件 5.自定義 resolveHTML 方法,來寫入 index.html 文件
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)})
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") })}
最終的結果就是在指定的文件中將樣式剝離開
但是那個最開始的index.html由于是包含全部的代碼,而后 在拆分樣式的時候存放的位置還是原來的,所以最終index.html的代碼不變
更多node相關知識,請訪問:nodejs 教程!
以上就是淺析node的path路徑模塊的詳細內容,更多請關注php中文網其它相關文章!