Home > Web Front-end > JS Tutorial > body text

A brief analysis of some APIs of the path module in node

青灯夜游
Release: 2022-05-26 13:00:12
forward
1961 people have browsed it

This article will introduce you to the path path module of node, introduce some APIs of the path built-in module, and also prepare a case for practice. I hope it will be helpful to everyone!

A brief analysis of some APIs of the path module in node

1. First introduction to path module

path module is officially provided by Node.js and is used for processing Path to module . 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 combine multiple path fragments Spliced ​​into a complete path string

The syntax format is

A brief analysis of some APIs of the path module in node

...paths(string) The sequence of path fragments is you All path series that need to be spliced

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)
Copy after login

A brief analysis of some APIs of the path module in node

##2.2 path. basename()

Use the path.basename() method to get the last part of the path. This method is often used to get the file name in the

path

Syntax format

A brief analysis of some APIs of the path module in node

    path required parameter, a string representing a path
  • Optional parameter, representing the file extension The name
  • 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)
    Copy after login

A brief analysis of some APIs of the path module in node

##2.3 path.extname()

path.extname() is used to get the file extension in the path

The format is

A brief analysis of some APIs of the path module in node

    path is a required parameter, a string representing a path
  • Return: Returns the obtained extension string
  • const path=require("path")
    
    const fpath='./a/b/c/d/index.html'
    
    const ftext =path.extname(fpath)
    
    console.log(ftext)
    Copy after login

A brief analysis of some APIs of the path module in node

3. Clock case practice

Split the provided code (one file has html, css, and js at the same time)

Split into three files: index.html index.css index.js and store them in a prepared file


Source code:

http://127.0. 0.1:5500/node/day1/static/index.html

3.1 Implementation steps

1. Create two regular expressions, respectively Used to match