Node.js開發(fā) path路徑模塊詳解
Nodejs—path 路徑模塊
1. 什么是 path 路徑模塊
path 模塊是 Node.js 官方提供的、用來處理路徑的模塊。它提供了一系列的方法和屬性,用來滿足用戶對路徑的處理需求。 例如:
(1) path.join() 方法,用來將多個路徑片段拼接成一個完整的路徑字符串
(2)path.basename() 方法,用來從路徑字符串中,將文件名解析出來
如果要在 JavaScript 代碼中,使用 path 模塊來處理路徑,則需要使用如下的方式先導入它:
2. 路徑拼接
1. path.join() 的語法格式
使用 path.join() 方法,可以把多個路徑片段拼接為完整的路徑字符串,語法格式如下: 參數(shù)解讀:
(1) ...paths <string> 路徑片段的序列
(2) 返回值: <string>
2. path.join() 的代碼示例
使用 path.join() 方法,可以把多個路徑片段拼接為完整的路徑字符串:
const path = require('path') const fs = require('fs') // 注意: ../ 會抵消前面的路徑 // const pathStr = path.join('/a', '/b/c', '../../', './d', 'e') // console.log(pathStr) // \a\b\d\e // fs.readFile(__dirname + '/files/1.txt') fs.readFile(path.join(__dirname, './files/1.txt'), 'utf8', function(err, dataStr) { if (err) { return console.log(err.message) } console.log(dataStr) })
注意:今后凡是涉及到路徑拼接的操作,都要使用 path.join() 方法進行處理。不要直接使用 + 進行字符串的拼接。
3. 獲取路徑中的文件名
1. path.basename() 的語法格式
使用 path.basename() 方法,可以獲取路徑中的最后一部分,經(jīng)常通過這個方法獲取路徑中的文件名,語法格式如下: 參數(shù)解讀:
(1) path 必選參數(shù),表示一個路徑的字符串
(2) ext 可選參數(shù),表示文件擴展名
(3) 返回: 表示路徑中的最后一部分
2. path.basename() 的代碼示例
使用 path.basename() 方法,可以從一個文件路徑中,獲取到文件的名稱部分:
const path = require('path') // 定義文件的存放路徑 const fpath = '/a/b/c/index.html' // 獲取完整的文件名 // const fullName = path.basename(fpath) // console.log(fullName) // 獲取文件名(無擴展名) const nameWithoutExt = path.basename(fpath, '.html') console.log(nameWithoutExt)
4. 獲取路徑中的文件擴展名
1. path.extname() 的語法格式
使用 path.extname() 方法,可以獲取路徑中的擴展名部分,語法格式如下: 參數(shù)解讀:
(1) path<string> 必選參數(shù),表示一個路徑的字符串
(2) 返回: <string> 返回得到的擴展名字符串
2. path.extname() 的代碼示例
使用 path.extname() 方法,可以獲取路徑中的擴展名部分:
const path = require('path') // 這是文件的存放路徑 const fpath = '/a/b/c/index.html' // 輸出文件路徑中的擴展名 const fext = path.extname(fpath) console.log(fext)
5. 綜合案例 - 時鐘案例
1. 案例要實現(xiàn)的功能
將素材目錄下的 index.html 頁面, 拆分成三個文件,分別是:
(1) index.css
(2) index.js
(3)index.html 并且將拆分出來的 3 個文件,存放到 clock 目錄中。
2. 案例的實現(xiàn)步驟
① 創(chuàng)建兩個正則表達式,分別用來匹配 <style> 和 <script> 標簽
② 使用 fs 模塊,讀取需要被處理的 HTML 文件
③ 自定義 resolveCSS 方法,來寫入 index.css 樣式文件
④ 自定義 resolveJS 方法,來寫入 index.js 腳本文件
⑤ 自定義 resolveHTML 方法,來寫入 index.html 文件
3.步驟
步驟1 - 導入需要的模塊并創(chuàng)建正則表達式
步驟2 - 使用 fs 模塊讀取需要被處理的 html 文件
步驟3 – 自定義 resolveCSS 方法
步驟4 – 自定義 resolveJS 方法
步驟5 – 自定義 resolveHTML 方法
4. 案例代碼
(1)index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>index首頁</title> <style> html, body { margin: 0; padding: 0; height: 100%; background-image: linear-gradient(to bottom right, red, gold); } .box { width: 400px; height: 250px; background-color: rgba(255, 255, 255, 0.6); border-radius: 6px; position: absolute; left: 50%; top: 40%; transform: translate(-50%, -50%); box-shadow: 1px 1px 10px #fff; text-shadow: 0px 1px 30px white; display: flex; justify-content: space-around; align-items: center; font-size: 70px; user-select: none; padding: 0 20px; /* 盒子投影 */ -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0%, transparent), to(rgba(250, 250, 250, .2))); } </style> </head> <body> <div class="box"> <div id="HH">00</div> <div>:</div> <div id="mm">00</div> <div>:</div> <div id="ss">00</div> </div> <script> window.onload = function () { // 定時器,每隔 1 秒執(zhí)行 1 次 setInterval(() => { var dt = new Date() var HH = dt.getHours() var mm = dt.getMinutes() var ss = dt.getSeconds() // 為頁面上的元素賦值 document.querySelector('#HH').innerHTML = padZero(HH) document.querySelector('#mm').innerHTML = padZero(mm) document.querySelector('#ss').innerHTML = padZero(ss) }, 1000) } // 補零函數(shù) function padZero(n) { return n > 9 ? n : '0' + n } </script> </body> </html>
(2) 時鐘案例.js
// 1.1 導入 fs 模塊 const fs = require('fs') // 1.2 導入 path 模塊 const path = require('path') // 1.3 定義正則表達式,分別匹配 <style></style> 和 <script></script> 標簽 const regStyle = /<style>[\s\S]*<\/style>/ const regScript = /<script>[\s\S]*<\/script>/ // 2.1 調用 fs.readFile() 方法讀取文件 fs.readFile(path.join(__dirname, '../素材/index.html'), 'utf8', function(err, dataStr) { // 2.2 讀取 HTML 文件失敗 if (err) { return console.log('讀取HTML文件失??!' + err.message) } // 2.3 讀取文件成功后,調用對應的三個方法,分別拆解出 css, js, html 文件 resolveCSS(dataStr) resolveJS(dataStr) resolveHTML(dataStr) }) // 3.1 定義處理 css 樣式的方法 function resolveCSS(htmlStr) { // 3.2 使用正則提取需要的內容 const r1 = regStyle.exec(htmlStr) // 3.3 將提取出來的樣式字符串,進行字符串的 replace 替換操作 const newCSS = r1[0].replace('<style>', '').replace('</style>', '') // 3.4 調用 fs.writeFile() 方法,將提取的樣式,寫入到 clock 目錄中 index.css 的文件里面 fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, function(err) { if (err) { return console.log('寫入 CSS 樣式失??!' + err.message) } console.log('寫入樣式文件成功!') }) } // 4.1 定義處理 js 腳本的方法 function resolveJS(htmlStr) { // 4.2 通過正則,提取對應的 <script></script> 標簽內容 const r2 = regScript.exec(htmlStr) // 4.3 將提取出來的內容,做進一步的處理 const newJS = r2[0].replace('<script>', '').replace('</script>', '') // 4.4 將處理的結果,寫入到 clock 目錄中的 index.js 文件里面 fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, function(err) { if (err) return console.log('寫入 JavaScript 腳本失敗!' + err.message) console.log('寫入 JS 腳本成功!') }) } // 5.1 定義處理 HTML 結構的方法 function resolveHTML(htmlStr) { // 5.2 將字符串調用 replace 方法,把內嵌的 style 和 script 標簽,替換為外聯(lián)的 link 和 script 標簽 const newHTML = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css" rel="external nofollow" />').replace(regScript, '<script src="./index.js"></script>') // 5.3 寫入 index.html 這個文件 fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, function(err) { if (err) return console.log('寫入 HTML 文件失??!' + err.message) console.log('寫入 HTML 頁面成功!') }) }
(3)index.css
html, body { margin: 0; padding: 0; height: 100%; background-image: linear-gradient(to bottom right, red, gold); } .box { width: 400px; height: 250px; background-color: rgba(255, 255, 255, 0.6); border-radius: 6px; position: absolute; left: 50%; top: 40%; transform: translate(-50%, -50%); box-shadow: 1px 1px 10px #fff; text-shadow: 0px 1px 30px white; display: flex; justify-content: space-around; align-items: center; font-size: 70px; user-select: none; padding: 0 20px; /* 盒子投影 */ -webkit-box-reflect: below 0px -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0%, transparent), to(rgba(250, 250, 250, .2))); }
(4)index.js
window.onload = function () { // 定時器,每隔 1 秒執(zhí)行 1 次 setInterval(() => { var dt = new Date() var HH = dt.getHours() var mm = dt.getMinutes() var ss = dt.getSeconds() // 為頁面上的元素賦值 document.querySelector('#HH').innerHTML = padZero(HH) document.querySelector('#mm').innerHTML = padZero(mm) document.querySelector('#ss').innerHTML = padZero(ss) }, 1000) } // 補零函數(shù) function padZero(n) { return n > 9 ? n : '0' + n }
5. 案例的兩個注意點
① fs.writeFile() 方法只能用來創(chuàng)建文件,不能用來創(chuàng)建路徑
② 重復調用 fs.writeFile() 寫入同一個文件,新寫入的內容會覆蓋之前的舊內容
補充:
Node.js開發(fā)-path模塊
path模塊
path 模塊提供了 操作路徑
的功能,將介紹如下幾個較為常用的幾個 API:
API | 說明 |
---|---|
path.resolve | 拼接規(guī)范的絕對路徑 常用 |
path.sep | 獲取操作系統(tǒng)的路徑分隔符 |
path.parse | 解析路徑并返回對象 |
path.basename | 獲取路徑的基礎名稱 |
path.dirname | 獲取路徑的目錄名 |
path.extname | 獲得路徑的擴展名 |
// 導入path模塊 const path = require("path"); // resolve 解決 console.log(path.resolve(__dirname, "index.html")); // sep 分隔符 console.log(path.sep); // parse 解析 let str = "F:\\Work\\VSCode-node.js\\3-path\\path.js"; console.log(path.parse(str)); // basename console.log(path.basename(str)); // dirname console.log(path.dirname(str)); // extname console.log(path.extname(str));
到此這篇關于Node.js開發(fā) path路徑模塊詳解的文章就介紹到這了,更多相關Node.js path模塊內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決koa2 ctx.render is not a function報錯問題
這篇文章主要介紹了解決koa2 ctx.render is not a function報錯問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08