1. What is the path path module
The path module is a module officially provided by Node.js to process paths. It provides a series of methods and attributes to meet the user's processing requirements for paths.
method name | illustrate |
the path.join() | Used to concatenate multiple path fragments into a complete path string |
path.basename() | Used to parse the file name from the path string |
path.extname() | Get the extension part of the path |
If you want to use the path module to handle paths in your JavaScript code, you need to import it first as follows:
2. Path splicing
(1) Syntax format of path.join()
Using the path.join() method, multiple path fragments can be spliced into a complete path string. The syntax is as follows:
Interpretation of parameters:
- ...paths <string> sequence of path fragments
- Return value: <string>
(2) Code example of path.join()
Using the path.join() method, multiple path fragments can be spliced into a complete path string:
const path = require('path') const fs = require('fs') // Note: ../ will cancel out the preceding path // 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) })
Note: In the future, all operations involving path splicing must be processed using the path.join() method. Do not use + directly to concatenate strings.
3. Get the file name in the path
(1) The syntax format of path.basename()
The last part of the path can be obtained by using the path.basename() method. This method is often used to obtain the file name in the path. The syntax format is as follows:
Interpretation of parameters:
- path <string> Required parameter, a string representing a path
- ext <string> Optional parameter, indicating the file extension
- Returns: <string> indicating the last part of the path
(2) Code example
Using the path.basename() method, you can get the name part of a file from a file path:
const path = require('path') // Define the storage path of the file const fpath = '/a/b/c/index.html' const fullName = path.basename(fpath) console.log(fullName) // output index.html const nameWithoutExt = path.basename(fpath, '.html') console.log(nameWithoutExt) // output index
4. Get the file extension in the path
(1) Syntax format of path.extname()
Use the path.extname() method to get the extension part of the path. The syntax is as follows:
Interpretation of parameters:
- path <string> Required parameter, a string representing a path
- Returns: <string> Returns the obtained extension string
(2) sample code
Using the path.extname() method, you can get the extension part of the path:
const path = require('path') // This is the storage path of the file const fpath = '/a/b/c/index.html' const fext = path.extname(fpath) console.log(fext) // output.html
5. Comprehensive case
(1) Functions to be realized by the case
Split the index.html page under the material directory into three files, namely:
- index.css
- index.js
- index.html
And store the 3 split files in the clock directory.
original page
<!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 front page</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; /* box projection */ -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 () { // Timer, executed every 1 second setInterval(() => { var dt = new Date() var HH = dt.getHours() var mm = dt.getMinutes() var ss = dt.getSeconds() // Assign values to elements on the page document.querySelector('#HH').innerHTML = padZero(HH) document.querySelector('#mm').innerHTML = padZero(mm) document.querySelector('#ss').innerHTML = padZero(ss) }, 1000) } // zero padding function function padZero(n) { return n > 9 ? n : '0' + n } </script> </body> </html>
(2) Implementation steps of the case
- Create two regular expressions to match <style> and <script> tags respectively
- Using the fs module, read the HTML file that needs to be processed
- Customize the resolveCSS method to write the index.css style file
- Customize the resolveJS method to write the index.js script file
- Customize resolveHTML method to write index.html file
(3) Code implementation
// 1.1 Import fs module const fs = require('fs') // 1.2 Import path module const path = require('path') // 1.3 Define regular expressions to match <style></style> and <script></script> tags respectively const regStyle = /<style>[\s\S]*<\/style>/ const regScript = /<script>[\s\S]*<\/script>/ // 2.1 Call the fs.readFile() method to read the file fs.readFile(path.join(__dirname, '../material/index.html'), 'utf8', function(err, dataStr) { // 2.2 Failed to read HTML file if (err) return console.log('read HTML File failed!' + err.message) // 2.3 After reading the file successfully, call the corresponding three methods to disassemble the css, js, html files respectively resolveCSS(dataStr) resolveJS(dataStr) resolveHTML(dataStr) }) // 3.1 Define the method of processing css style function resolveCSS(htmlStr) { // 3.2 Use regular expressions to extract the required content const r1 = regStyle.exec(htmlStr) // 3.3 Perform the replace operation on the extracted style string const newCSS = r1[0].replace('<style>', '').replace('</style>', '') // 3.4 Call the fs.writeFile() method to write the extracted style into the index.css file in the clock directory fs.writeFile(path.join(__dirname, './clock/index.css'), newCSS, function(err) { if (err) return console.log('to write CSS Style failed!' + err.message) console.log('Write style file successfully!') }) } // 4.1 Define the method of processing js script function resolveJS(htmlStr) { // 4.2 Extract the content of the corresponding <script></script> tag through regularization const r2 = regScript.exec(htmlStr) // 4.3 Further process the extracted content const newJS = r2[0].replace('<script>', '').replace('</script>', '') // 4.4 Write the processing result to the index.js file in the clock directory fs.writeFile(path.join(__dirname, './clock/index.js'), newJS, function(err) { if (err) return console.log('to write JavaScript Script failed!' + err.message) console.log('to write JS Script succeeded!') }) } // 5.1 Define methods for handling HTML structures function resolveHTML(htmlStr) { // 5.2 Call the replace method on the string, and replace the embedded style and script tags with external link and script tags const newHTML = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css" />').replace(regScript, '<script src="./index.js"></script>') // 5.3 Write index.html to this file fs.writeFile(path.join(__dirname, './clock/index.html'), newHTML, function(err) { if (err) return console.log('to write HTML File failed!' + err.message) console.log('to write HTML Page successful!') }) }
(4) Two points for attention in the case
- The fs.writeFile() method can only be used to create files, not paths
- Call fs.writeFile() repeatedly to write to the same file, the newly written content will overwrite the previous old content