Table of contents
1.
Introduction
2.
Path Properties and Methods
2.1.
Path Methods
2.1.1.
path.basename(path[, ext])
2.1.2.
path.dirname( )
2.1.3.
path.extname()
2.1.4.
path.format()
2.1.5.
path.isAbsolute()
2.1.6.
path.join()
2.1.7.
path.normalize()
2.1.8.
path.parse()
2.1.9.
path.relative(from,to)
2.1.10.
path.resolve()
2.1.11.
path.toNamespacedPath()
2.2.
Path Properties
2.2.1.
path.delimiter
2.2.2.
path.sep
2.2.3.
path.win32
2.2.4.
path.posix()
3.
Frequently Asked Questions
3.1.
Why do we use a path module?
3.2.
What is the path of the Node module folder?
3.3.
What is const path = require('path')?
4.
Conclusion
Last Updated: Jan 21, 2025
Easy

Path Module in Node.js

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Path module in Node.js provides handy functionality to work with files and directories. It is a great module to interact with and access various files.

Path Module in Node.js

Since it is a part of Node.js core, you don’t need to install it. You can include the Path module in your application by using the following syntax:

var path = require('path');

 

Path Properties and Methods

The path properties and methods are fundamental when it comes to the path module in Node.js. One important thing to keep in mind is that the path module is platform-specific. Let’s have a look at some of the methods and properties of the path module in Node.js.

Path Methods

path.basename(path[, ext])

path.basename() returns the last portion of a path. The file extension can be filtered out with a second parameter:

path.basename('/foo/bar/baz/asdf/apple.html');
// Returns: 'apple.html'

path.basename('/foo/bar/baz/asdf/apple.html', '.html');
// Returns: 'apple'


path.dirname( )

path.dirname() returns the directory name of the path.

path.dirname('/foo/bar/baz/asdf/quux');
// Returns: '/foo/bar/baz/asdf' 


path.extname()

The path.extname() method returns the file path's extension.

It starts at the last occurrence of the ‘.’ (period) character and ends at the end of the string in the path's last section. We get an empty string if there is no ’‘.’ in the path's last segment or if there are no ‘.’ characters other than the first character of the path's basename.

path.extname('index.html');
// Returns: '.html'

path.extname('index.hello.md');
// Returns: '.md'

path.extname('index.');
// Returns: '.'

path.extname('index');
// Returns: ''

path.extname('.index');
// Returns: ''

path.extname('.index.md');
// Returns: '.md'


path.format()

From an object, the path.format() method returns a path string. path.format()  is the opposite of path.parse(). path.format takes a JavaScript object with the following keys as an argument:

  • root: the root
  • dir: the folder path starting from the root
  • base: the file name + extension
  • name: the file name
  • ext: the file extension

 

When giving the pathObject properties, keep in mind that there are some cases where one property takes precedence over another:

  • If pathObject.dir is supplied, pathObject.root is ignored.
  • If pathObject.base exists, pathObject.ext and pathObject.name are ignored.

 

On POSIX (Portable Operating System Interface):

// If 'dir', 'root' and 'base' are provided,
// 'root' is ignored here.

path.format({
  root: '/ignored',
  dir: '/home/user/dir',
  base: 'fileABC.txt'
});
// Returns: '/home/user/dir/fileABC.txt'


// 'root' will be only used if 'dir' is not directly specified.
// The platform separator will not be included if only 'root' is provided or if 'dir' is equal to 'root'. 'ext' will not be used.

path.format({
  root: '/',
  base: 'fileABC.txt',
  ext: 'ignored'
});
// Returns: '/fileABC.txt'


// 'name' + 'ext' will be used if 'base' is not specified.
path.format({
  root: '/',
  name: 'fileABC',
  ext: '.txt'
});
// Returns: '/fileABC.txt'

 

On Windows:

path.format({
  dir: 'C:\\path\\dir',
  base: 'fileABC.txt'
});
// Returns: 'C:\\path\\dir\\fileABC.txt'


path.isAbsolute()

path.isAbsolute() determines whether or not the path is an absolute path.

False is returned if the specified route is a zero-length string.

 

On POSIX:

path.isAbsolute('/foo/bar'); // True
path.isAbsolute('/baz/..');  // True
path.isAbsolute('qux/');     // False
path.isAbsolute('.');        // False

 

On Windows:

path.isAbsolute('//server');    // True
path.isAbsolute('\\\\server');  // True
path.isAbsolute('C:/foo/..');   // True
path.isAbsolute('C:\\foo\\..'); // True
path.isAbsolute('bar\\baz');    // False
path.isAbsolute('bar/baz');     // False
path.isAbsolute('.');           // False


path.join()

The path.join() joins two or more path segments.

This method merges all specified path segments using the platform-specific separator as a delimiter, then normalises the result.

Path segments with zero-length are directly ignored. If the path string that is joined has a string length of zero, the current working directory will be returned as '.'.

path.join('/foo', 'bar', 'baz/asdf', 'apple', '..');
// Returns: '/foo/bar/baz/asdf'

path.join('foo', {}, 'bar');
// Throws 'TypeError: Path must be a string. Received {}'


path.normalize()

When a path contains relative specifiers like ‘.’ or ‘..’ , or double slashes, it tries to calculate the true path:

When several consecutive path segment separation characters (e.g., / on POSIX and or / on Windows) are discovered, they are replaced by a single instance of the platform-specific path segment separator (/ on POSIX and / on Windows). Separators at the end of the line are kept.

If the path is a zero-length string, the current working directory is returned as '.'.

 

On POSIX:

path.normalize('/foo/bar//baz/asdf/apple/..');
// Returns: '/foo/bar/baz/asdf'

 

On Windows:

path.normalize('C:\\temp\\\\foo\\bar\\..\\');
// Returns: 'C:\\temp\\foo\\'


path.parse()

The path.parse() method returns an object with properties that indicate important path elements. It ignores directory separators at the end of the path.

 

The properties of the returned object are as follows:

  • root: the root
  • dir: the folder path starting from the root
  • base: the file name + extension
  • name: the file name
path.parse('/home/user/dir/file.txt');
// Returns:
// { root: '/',
//   dir: '/home/user/dir',
//   base: 'file.txt',
//   ext: '.txt',
//   name: 'file' }


path.relative(from,to)

Based on the current working directory, the path.relative() method returns the relative path starting from ‘from’ till ‘to’. A zero-length string is produced if both from and to resolve to the same path after calling path.resolve() on both.

If a zero-length string is given as from or to, then the current working directory will be used.

path.relative('/data/orandea/test/grapes', '/data/orandea/impl/orange');
// Returns: '../../impl/orange'

A TypeError will be thrown if either from or to is not a string.

path.resolve()

The path.resolve() resolves a sequence of paths or route segments into an absolute path.

  • From right to left, the specified path sequence is processed, with each succeeding path being prepended until an absolute path is created.
  • If an absolute path cannot be produced after processing all specified path segments, the current working directory is utilized.
  • Unless the path resolves to the root directory, the path is normalized, and trailing slashes are eliminated.
  • Path segments with no length are ignored.
  • Path.resolve() returns the absolute path of the current working directory if no path segments are given.
path.resolve('/foo/bar', './gold');
// Returns: '/foo/bar/gold'

path.resolve('/foo/bar', '/tmp/fileABC/');
// Returns: '/tmp/fileABC'

path.resolve('wwwroot', 'static_files/png/', '../gif/imageOfCar.gif');
// If the current working directory is /home/myself/node,
// this returns '/home/myself/node/wwwroot/static_files/gif/imageOfCar.gif'


path.toNamespacedPath()

path.toNamespacedPath() returns an equivalent namespace-prefixed path for the provided path on Windows systems only. If the path is not a string, the path will be returned unchanged.

This strategy is only applicable on Windows computers. The technique is non-operational on POSIX platforms and always returns the path unchanged.

Path Properties

path.delimiter

path.delimiter() returns the delimiter specified for the platform:

; (semicolon) for Windows

: (colon) for POSIX 

 

On POSIX:

console.log(process.env.PATH);
// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'

process.env.PATH.split(path.delimiter);
// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']

 

On Windows:

console.log(process.env.PATH);
// Prints: 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'

process.env.PATH.split(path.delimiter);
// Returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']


path.sep

Provides a path segment separator that is platform-specific:

\ on Windows

/ on POSIX

 

on POSIX:

'foo/bar/baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']

 

On Windows:

The forward-slash (/) and backward slash (\) are both recognized as path segment separators on Windows; however, path methods only append backward slashes (\).

'foo\\bar\\baz'.split(path.sep);
// Returns: ['foo', 'bar', 'baz']


path.win32

The path.win32 gives you access to Windows-specific path methods.

The API can be accessed by calling require('path').win32 or require('path/win32').

path.posix()

The path.posix parameter gives you access to POSIX-specific path method implementations.

The API(Application Programming Interface) can be accessed via require('path').posix or require('path/posix').

Frequently Asked Questions

Why do we use a path module?

The path module in Node.js provides utilities for working with file and directory paths, helping in path resolution, manipulation, and normalization.

What is the path of the Node module folder?

The Node module folder is typically located in node_modules within your project directory, or globally in the system's Node.js installation folder.

What is const path = require('path')?

const path = require('path') imports the Node.js path module, allowing you to use its functions for path manipulation and file system operations in your code.

Conclusion

For working with files and directories, the Path module in Node.js contains many valuable functions. It's an excellent module for working with and accessing a wide range of file paths. The path module in Node.js is platform-specific. Its default behavior differs depending on the operating system on which a Node.js application is running.

Live masterclass