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:


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


Return the directory part of the path:

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


Return the extended part of the path

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


If it is an absolute path, return true

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


Connect two or more parts of a path:

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


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


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



The results are

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


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


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


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: