NodeJS ② (path path module)

what is path path module

The path module is an official module provided by Node.js to process paths. It provides a series of methods and properties to meet the user's processing requirements for paths.
E.g:

  • The path.join() method is used to concatenate multiple path fragments into a complete path string
  • The path.basename() method is used to parse the filename from the path string

If you want to use the path module to handle paths in JavaScript code, you need to import it first as follows:

const path = require('path');

path splicing

Using the path.join() method, multiple path fragments can be spliced ​​into a complete path string. The syntax format is as follows:
insert image description here
Parameter interpretation:

  • …paths <string> Sequence of path fragments
  • Return value: <string>

E.g:

const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
console.log(pathStr)  // \a\b\d\e

Note: .../ will offset the previous path

insert image description here
In the case of the above picture, the path module will automatically .omit that for us. If the plus sign is used to connect here, it will be combined into a wrong path and the file will not be found.

Therefore, it is recommended to use the path.join() method for all operations involving path splicing in the future. Do not use + directly to concatenate strings .

Get filename in path

Using the path.basename() method, you can get the last part of the path. This method is often used to get the file name in the path. The syntax format is as follows:
insert image description here
Parameter interpretation:

  • path <string> Required parameter, a string representing a path
  • ext <string> optional parameter indicating the file extension
  • Returns: <string> representing the last part of the path

E.g:

const path = require('path')

// 定义文件的存放路径
const fpath = '/a/b/c/index.html'

const fullName = path.basename(fpath)
console.log(fullName)   //index.html

const nameWithoutExt = path.basename(fpath, '.html')
console.log(nameWithoutExt)  //index

Get file extension in path

Using the path.extname() method, the extension part in the path can be obtained. The syntax format is as follows:
insert image description here
Parameter interpretation:

  • path <string> Required parameter, a string representing a path
  • Returns: <string> Returns the resulting extension string

E.g:

const path = require('path')

// 这是文件的存放路径
const fpath = '/a/b/c/index.html'

const fext = path.extname(fpath)
console.log(fext)  //.html

Guess you like

Origin blog.csdn.net/zyb18507175502/article/details/124272228