Technology Sharing

Node.js path module

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In Node.js,path Modules are used to process and convert file paths. The following are some commonly usedpath Module methods and their descriptions:

  1. path.basename(path[, ext])

    • Returns the last component of the path, which is the file name.
    • Example:
      const path = require('path');
      console.log(path.basename('/foo/bar/baz/asdf/quux.html')); // 输出: 'quux.html'
      console.log(path.basename('/foo/bar/baz/asdf/quux.html', '.html')); // 输出: 'quux'
      
  2. path.dirname(path)

    • Returns the directory portion of path.
    • Example:
      const path = require('path');
      console.log(path.dirname('/foo/bar/baz/asdf/quux.html')); // 输出: '/foo/bar/baz/asdf'
      
  3. path.extname(path)

    • Returns the extension of the path.
    • Example:
      const path = require('path');
      console.log(path.extname('/foo/bar/baz/asdf/quux.html')); // 输出: '.html'
      
  4. path.join([...paths])

    • Joins all of the given path segments together and normalizes the resulting path.
    • Example:
      const path = require('path');
      console.log(path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')); // 输出: '/foo/bar/baz/asdf'
      
  5. path.resolve([...paths])

    • Resolves a path or path fragment to an absolute path.
    • Example:
      const path = require('path');
      console.log(path.resolve('/foo/bar', './baz')); // 输出: '/foo/bar/baz'
      console.log(path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')); // 输出: '/tmp/subfile'
      
  6. path.isAbsolute(path)

    • Determines whether the given path is an absolute path.
    • Example:
      const path = require('path');
      console.log(path.isAbsolute('/foo/bar')); // 输出: true
      console.log(path.isAbsolute('quux/')); // 输出: false
      

These methods provide powerful functions for manipulating file paths to facilitate the management of files and directories. path module, you first need to userequire('path') Bring it in.