The path module is a built-in module in nodejs for processing file/directory paths. It can be regarded as a toolbox, providing many methods for us to use, of course all related to path processing. At the same time, the path module appears frequently in front-end development, such as when configuring webpack. This article will talk about the path module of node.
node’s path module
Foreword: Through this article you will understand node Some API
of the path built-in module can be viewed on the node official website if necessary. Of course practice is greater than theory
So I prepared a case for practice
1. First introduction to the path module
The path module is a module officially provided by Node.js for processing paths. It provides a series of methods and attributes to meet users' needs for path processing.
2.path module API
2.1 path.join()
path.join() method, used to splice multiple path fragments into a complete path string
The syntax format is
…paths(string) The sequence of path fragments is all the path series you need to splice. [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
##It should be noted that the returned value is string
//引入path模块 const path=require("path") //书写要拼接的路径 const pathStr=path.join('/a','/b/c','../','./d','e') console.log(pathStr)
##2.2 path.basename()
Use path.basename() method, The last part of the path can be obtained. This method is often used to obtain the file name in thepath Syntax format
- Optional parameter, representing the file extension
- Represents the last part of the 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)
2.3 path.extname()
path.extname() is used to get the file extension in the pathThe format is
- path is a required parameter, a string representing a path
- Return: Return the obtained extension string
-
const path=require("path") const fpath='./a/b/c/d/index.html' const ftext =path.extname(fpath) console.log(ftext)
3. Clock case practice
Split the provided code (one file has html, css, and js at the same time)Split into three files, namely index.html index.css index. js and store it in a prepared file
Source code Right click to view the source code
3.1 Implementation steps
1. Create two regular expressions to match
3.1.1 Steps 1 - Import the required modules and create regular expressionconst 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)
})
3.1.2 Custom resolveCSS resolveHTML resolveJS methodfunction 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")
})
}
Finally The result is that the style is stripped out in the specified file
. However, since the initial index.html contains all the code, the location where is stored when the style is split is still the same. Original, so the code of final index.html remains unchanged
For more node-related knowledge, please visit: nodejs tutorial!
The above is the detailed content of A brief analysis of node's path module. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.