Node path module

Node.js path module provides useful functions to interact with file paths

ThispathThe module provides many very useful functions to access and interact with the file system.

No need to install. As part of the Node core, it can be used by requesting:

const path = require('path')

This module providespath.sepProvide a path segment separator (\On Windows, and/On Linux/macOS), andpath.delimiterProvide a path delimiter (;On Windows, and:On Linux/macOS).

these arepathmethod:

path.basename()

Return the last part of the path. The second parameter can filter out the file extension:

require('path').basename('/test/something') //something
require('path').basename('/test/something.txt') //something.txt
require('path').basename('/test/something.txt', '.txt') //something

path.dirname()

Return the directory part of the path:

require('path').dirname('/test/something') // /test
require('path').dirname('/test/something/file.txt') // /test/something

path.extname()

Return the extended part of the path

require('path').extname('/test/something') // ''
require('path').extname('/test/something/file.txt') // '.txt'

path.isAbsolute()

If it is an absolute path, return true

require('path').isAbsolute('/test/something') // true
require('path').isAbsolute('./test/something') // false

path.join()

Connect two or more parts of a path:

const name = 'flavio'
require('path').join('/', 'users', name, 'notes.txt') //'/users/flavio/notes.txt'

path.normalize()

When trying to calculate the actual path that contains relative specifiers, for example.or..Or double slash:

require('path').normalize('/users/flavio/..//test.txt') ///users/test.txt

path.parse()

Analyze the path of the object with its constituent segments:

  • root: Root
  • dir: The folder path from the root
  • base: File name + extension
  • name:file name
  • ext: File extension

example:

require('path').parse('/users/test.txt')

The results are

{
  root: '/',
  dir: '/users',
  base: 'test.txt',
  ext: '.txt',
  name: 'test'
}

path.relative()

Accept 2 paths as parameters. According to the current working directory, return the relative path from the first path to the second path.

example:

require('path').relative('/Users/flavio', '/Users/flavio/test.txt') //'test.txt'
require('path').relative('/Users/flavio', '/Users/flavio/something/test.txt') //'something/test.txt'

path.resolve()

You can use the following method to get the absolute path calculation of the relative pathpath.resolve():

path.resolve('flavio.txt') //'/Users/flavio/flavio.txt' if run from my home folder

By specifying the second parameter,resolveThe first will be used as the basis for the second:

path.resolve('tmp', 'flavio.txt')//'/Users/flavio/tmp/flavio.txt' if run from my home folder

If the first parameter starts with a slash, it means it is an absolute path:

path.resolve('/etc', 'flavio.txt')//'/etc/flavio.txt'

Download mine for freeNode.js manual


More node tutorials: