Path route module

  1. path path module

    The path module is officially provided by Node.js and is used to process paths. It has methods for dealing with paths, such as path.join() to join paths, path.basename() to parse filenames, etc.


  2. import path module

    1
    const path = require('path')

  1. Path splicing: path.join()

    The path.join() method can join multiple path fragments into a complete path string.

    1
    path.join([...paths])

    The parameter …paths is of type string and is a sequence of path fragments. The return value is the assembled path string.

    But in path fragments, be aware that ../ will cause the previous layer of the path to be canceled. Whereas ./ does not negate the previous path. If you need to offset the upper two layers of paths, you should use ../../ .

    1
    2
    const pathStr = path.join('/a', '/b/c', '../', './d', 'e') //result is \a\b\d\e
    const pathStr2 = path.join(__dirname, './files/1.txt') //The complete absolute path can be spliced out.

    In the future, operations involving path splicing should be handled with the path.join() method, and do not use + for string splicing. The reason is that if you thank a . such as ./ , the path will be wrong after splicing with a plus sign. But path.join() will take care of the extra . .

    1
    fs.readFile(path.join(__dirname, '/files/1.txt'), 'utf8', function(){})

  1. Get the filename in the path: path.basename()

    The path.basename() method can get the last part of the path, which is usually used to get the filename in the path.

    1
    path.basename(path[, ext])

    Parameter 1: required parameter, path string.

    Parameter 2: Optional parameter, indicating the file extension.

    If the second parameter is not passed in, the returned result is the file name with the extension, such as index.html. Add the second parameter passed in, such as '.html', and the returned result is the file name without extension, such as index.

    1
    2
    path.basename(filePath1) //The result is index.html
    path.basename(filePath1, '.html') //The result is index

  1. Get the file extension in the path: path.extname()

    The path.extname() method can get the extension part of the path. The return value is an extension starting with ..

    1
    path.extname(path)

Share