Node.js開發(fā) path路徑模塊詳解
Nodejs—path 路徑模塊
1. 什么是 path 路徑模塊
path 模塊是 Node.js 官方提供的、用來處理路徑的模塊。它提供了一系列的方法和屬性,用來滿足用戶對路徑的處理需求。 例如:
(1) path.join() 方法,用來將多個(gè)路徑片段拼接成一個(gè)完整的路徑字符串
(2)path.basename() 方法,用來從路徑字符串中,將文件名解析出來
如果要在 JavaScript 代碼中,使用 path 模塊來處理路徑,則需要使用如下的方式先導(dǎo)入它:

2. 路徑拼接
1. path.join() 的語法格式
使用 path.join() 方法,可以把多個(gè)路徑片段拼接為完整的路徑字符串,語法格式如下: 參數(shù)解讀:
(1) ...paths <string> 路徑片段的序列
(2) 返回值: <string>
2. path.join() 的代碼示例
使用 path.join() 方法,可以把多個(gè)路徑片段拼接為完整的路徑字符串:

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() 方法進(jìn)行處理。不要直接使用 + 進(jìn)行字符串的拼接。
3. 獲取路徑中的文件名
1. path.basename() 的語法格式
使用 path.basename() 方法,可以獲取路徑中的最后一部分,經(jīng)常通過這個(gè)方法獲取路徑中的文件名,語法格式如下: 參數(shù)解讀:
(1) path 必選參數(shù),表示一個(gè)路徑的字符串
(2) ext 可選參數(shù),表示文件擴(kuò)展名
(3) 返回: 表示路徑中的最后一部分
2. path.basename() 的代碼示例
使用 path.basename() 方法,可以從一個(gè)文件路徑中,獲取到文件的名稱部分:

const path = require('path')
// 定義文件的存放路徑
const fpath = '/a/b/c/index.html'
// 獲取完整的文件名
// const fullName = path.basename(fpath)
// console.log(fullName)
// 獲取文件名(無擴(kuò)展名)
const nameWithoutExt = path.basename(fpath, '.html')
console.log(nameWithoutExt)4. 獲取路徑中的文件擴(kuò)展名
1. path.extname() 的語法格式
使用 path.extname() 方法,可以獲取路徑中的擴(kuò)展名部分,語法格式如下: 參數(shù)解讀:

(1) path<string> 必選參數(shù),表示一個(gè)路徑的字符串
(2) 返回: <string> 返回得到的擴(kuò)展名字符串
2. path.extname() 的代碼示例
使用 path.extname() 方法,可以獲取路徑中的擴(kuò)展名部分:

const path = require('path')
// 這是文件的存放路徑
const fpath = '/a/b/c/index.html'
// 輸出文件路徑中的擴(kuò)展名
const fext = path.extname(fpath)
console.log(fext)5. 綜合案例 - 時(shí)鐘案例
1. 案例要實(shí)現(xiàn)的功能
將素材目錄下的 index.html 頁面, 拆分成三個(gè)文件,分別是:

(1) index.css
(2) index.js
(3)index.html 并且將拆分出來的 3 個(gè)文件,存放到 clock 目錄中。
2. 案例的實(shí)現(xiàn)步驟
① 創(chuàng)建兩個(gè)正則表達(dá)式,分別用來匹配 <style> 和 <script> 標(biāo)簽
② 使用 fs 模塊,讀取需要被處理的 HTML 文件
③ 自定義 resolveCSS 方法,來寫入 index.css 樣式文件
④ 自定義 resolveJS 方法,來寫入 index.js 腳本文件
⑤ 自定義 resolveHTML 方法,來寫入 index.html 文件
3.步驟
步驟1 - 導(dǎo)入需要的模塊并創(chuàng)建正則表達(dá)式

步驟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 () {
// 定時(shí)器,每隔 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)
}
// 補(bǔ)零函數(shù)
function padZero(n) {
return n > 9 ? n : '0' + n
}
</script>
</body>
</html>(2) 時(shí)鐘案例.js
// 1.1 導(dǎo)入 fs 模塊
const fs = require('fs')
// 1.2 導(dǎo)入 path 模塊
const path = require('path')
// 1.3 定義正則表達(dá)式,分別匹配 <style></style> 和 <script></script> 標(biāo)簽
const regStyle = /<style>[\s\S]*<\/style>/
const regScript = /<script>[\s\S]*<\/script>/
// 2.1 調(diào)用 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 讀取文件成功后,調(diào)用對應(yīng)的三個(gè)方法,分別拆解出 css, js, html 文件
resolveCSS(dataStr)
resolveJS(dataStr)
resolveHTML(dataStr)
})
// 3.1 定義處理 css 樣式的方法
function resolveCSS(htmlStr) {
// 3.2 使用正則提取需要的內(nèi)容
const r1 = regStyle.exec(htmlStr)
// 3.3 將提取出來的樣式字符串,進(jìn)行字符串的 replace 替換操作
const newCSS = r1[0].replace('<style>', '').replace('</style>', '')
// 3.4 調(diào)用 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 通過正則,提取對應(yīng)的 <script></script> 標(biāo)簽內(nèi)容
const r2 = regScript.exec(htmlStr)
// 4.3 將提取出來的內(nèi)容,做進(jìn)一步的處理
const newJS = r2[0].replace('<script>', '').replace('</script>', '')
// 4.4 將處理的結(jié)果,寫入到 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 結(jié)構(gòu)的方法
function resolveHTML(htmlStr) {
// 5.2 將字符串調(diào)用 replace 方法,把內(nèi)嵌的 style 和 script 標(biāo)簽,替換為外聯(lián)的 link 和 script 標(biāo)簽
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 這個(gè)文件
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 () {
// 定時(shí)器,每隔 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)
}
// 補(bǔ)零函數(shù)
function padZero(n) {
return n > 9 ? n : '0' + n
}5. 案例的兩個(gè)注意點(diǎn)
① fs.writeFile() 方法只能用來創(chuàng)建文件,不能用來創(chuàng)建路徑
② 重復(fù)調(diào)用 fs.writeFile() 寫入同一個(gè)文件,新寫入的內(nèi)容會覆蓋之前的舊內(nèi)容
補(bǔ)充:
Node.js開發(fā)-path模塊
path模塊
path 模塊提供了 操作路徑 的功能,將介紹如下幾個(gè)較為常用的幾個(gè) API:
| API | 說明 |
|---|---|
| path.resolve | 拼接規(guī)范的絕對路徑 常用 |
| path.sep | 獲取操作系統(tǒng)的路徑分隔符 |
| path.parse | 解析路徑并返回對象 |
| path.basename | 獲取路徑的基礎(chǔ)名稱 |
| path.dirname | 獲取路徑的目錄名 |
| path.extname | 獲得路徑的擴(kuò)展名 |
// 導(dǎo)入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));到此這篇關(guān)于Node.js開發(fā) path路徑模塊詳解的文章就介紹到這了,更多相關(guān)Node.js path模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js從字符串生成文件流的實(shí)現(xiàn)方法
這篇文章主要介紹了Node.js從字符串生成文件流的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
解決koa2 ctx.render is not a function報(bào)錯問題
這篇文章主要介紹了解決koa2 ctx.render is not a function報(bào)錯問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08
NodeJS搭建HTTP服務(wù)器的實(shí)現(xiàn)步驟
NodeJS中用來創(chuàng)建服務(wù)的模塊是http核心模塊,本篇就來介紹關(guān)于使用http模塊搭建HTTP服務(wù)器和客戶端的方法,以及模塊的基本 API,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2018-10-10

