path

The path Module

The path module in Node.js is a powerful tool for manipulating and working with file and directory paths. It provides a variety of functions that can be used to:

  • Join paths together

  • Extract path components (e.g., filename, extension, directory)

  • Check if a path exists

  • Convert paths to absolute or relative paths

Joining Paths

One of the most common tasks when working with paths is joining them together. This can be done using the path.join() function. For example:

const path1 = "home";
const path2 = "username";
const fullPath = path.join(path1, path2); // 'home/username'

Extracting Path Components

The path module also provides a number of functions for extracting individual components from a path. These include:

  • path.basename() - returns the filename (without the directory)

  • path.dirname() - returns the directory (without the filename)

  • path.extname() - returns the file extension (e.g., ".js")

For example:

const path = "home/username/index.js";
const filename = path.basename(); // 'index.js'
const directory = path.dirname(); // 'home/username'
const extension = path.extname(); // '.js'

Checking if a Path Exists

The path module also provides a function for checking if a path exists. This can be useful for determining if a file or directory exists before trying to open or use it.

The path.existsSync() function takes a path as an argument and returns a boolean value indicating whether the path exists. For example:

const path = "home/username/index.js";
const exists = path.existsSync(); // true

Converting Paths to Absolute or Relative Paths

The path module also provides functions for converting paths to absolute or relative paths. An absolute path is a complete path from the root of the filesystem, while a relative path is a path that is relative to the current directory.

The path.resolve() function can be used to convert a relative path to an absolute path. For example:

const path = "home/username/index.js";
const absolutePath = path.resolve(); // '/home/username/index.js'

The path.relative() function can be used to convert an absolute path to a relative path. For example:

const path = "/home/username/index.js";
const relativePath = path.relative(); // 'home/username/index.js'

Real World Applications

The path module is a versatile tool that can be used in a variety of real-world applications. Some examples include:

  • Joining paths to access files and directories

  • Extracting path components to display file information in a user interface

  • Checking if paths exist before trying to open them

  • Converting paths to absolute or relative paths for use in different contexts

Complete Code Implementations

Here are some complete code implementations of the path module functions:

// Join two paths together
const path1 = "home";
const path2 = "username";
const fullPath = path.join(path1, path2); // 'home/username'

// Extract the filename from a path
const path = "home/username/index.js";
const filename = path.basename(); // 'index.js'

// Check if a path exists
const path = "home/username/index.js";
const exists = path.existsSync(); // true

// Convert a relative path to an absolute path
const path = "home/username/index.js";
const absolutePath = path.resolve(); // '/home/username/index.js'

// Convert an absolute path to a relative path
const path = "/home/username/index.js";
const relativePath = path.relative(); // 'home/username/index.js'

Understanding the node:path Module

The node:path module in Node.js provides functions for working with file and directory paths. Depending on the operating system (OS) you're using (Windows or POSIX, which includes Linux, macOS, etc.), the default behavior of this module can vary.

Windows vs. POSIX Paths

On Windows, paths use backslashes (\) to separate directories, while on POSIX systems, forward slashes (/) are used. For example, on Windows, the path to a file might be C:\Users\John\Documents\myfile.txt, while on POSIX, it could be /home/john/documents/myfile.txt.

Consistent Path Handling

To ensure consistent results when working with Windows paths on any OS, use the path.win32 module. This module provides functions that handle Windows-style paths correctly. Similarly, to work with POSIX paths consistently on any OS, use the path.posix module.

Example:

// Get the file name without the path (basename)
const win32Path = "C:\\Users\\John\\Documents\\myfile.txt";
const posixPath = "/home/john/documents/myfile.txt";

// Use the correct module for each path type
const win32Basename = path.win32.basename(win32Path); // Output: 'myfile.txt'
const posixBasename = path.posix.basename(posixPath); // Output: 'myfile.txt'

Per-Drive Working Directory on Windows

On Windows, the path module follows the concept of a per-drive working directory. This means that if you specify a drive letter without a backslash, it will default to the current working directory on that drive.

Example:

// Get the current working directory on drive C:
const cwd = path.resolve("C:"); // Output: 'C:\\Users\\John'

// Resolve a path relative to the C: drive
const resolvedPath = path.resolve("C:users\\john\\documents"); // Output: 'C:\\Users\\John\\Documents'

Potential Applications

The node:path module is used in various real-world applications, such as:

  • Reading and writing files

  • Manipulating directory structures

  • Creating and parsing URLs

  • Working with database paths


path.basename(path[, suffix])

The path.basename() method returns the last part of a file path. It's like the basename command in Unix.

Parameters:

  • path: The file path.

  • suffix (optional): A suffix to remove from the file name.

Return value:

A string containing the last part of the file path.

Example:

const path = require("path");

path.basename("/foo/bar/baz/asdf/quux.html"); // 'quux.html'

Real-world application:

  • Getting the file name from a URL:

const url = "https://example.com/foo/bar/baz/asdf/quux.html";
const fileName = path.basename(url); // 'quux.html'
  • Removing the file extension from a file name:

const fileName = "quux.html";
const fileNameWithoutExtension = path.basename(fileName, ".html"); // 'quux'

Potential applications:

The path.basename() method can be used in any application that needs to work with files or file paths. Some examples include:

  • File browsers

  • File managers

  • Web servers

  • Command-line tools


path.delimiter

The path.delimiter property is a string that represents the platform-specific path delimiter. This property is used to separate directories in a file path.

On Windows, the path delimiter is ;. For example, the following file path uses the ; delimiter to separate the bin directory from the Program Files directory:

C:\bin;C:\Program Files

On POSIX systems (such as Linux and macOS), the path delimiter is :. For example, the following file path uses the : delimiter to separate the bin directory from the usr directory:

/bin:/usr

The path.delimiter property can be used to split a file path into an array of directories. For example, the following code splits the file path /bin:/usr into an array of two directories:

const path = require('path');

const filePath = '/bin:/usr';
const directories = filePath.split(path.delimiter);

console.log(directories); // ['/bin', '/usr']

Real-World Applications

The path.delimiter property can be used in a variety of real-world applications, such as:

  • Parsing file paths: The path.delimiter property can be used to parse a file path into an array of directories. This can be useful for tasks such as finding the parent directory of a file or checking if a file exists in a particular directory.

  • Creating file paths: The path.delimiter property can be used to create a file path from an array of directories. This can be useful for tasks such as creating a new file or opening an existing file.

  • Cross-platform file paths: The path.delimiter property can be used to create file paths that are compatible with both Windows and POSIX systems. This can be useful for tasks such as sharing files between different operating systems.


Simplified Explanation:

The path.dirname() method in Node.js's path module helps you get the directory name (the folder path) from a given file path.

Detailed Explanation:

Imagine you have a file named "my_file.txt" located inside the folder "my_folder", which is further inside the folder "my_parent_folder". If you give the path to path.dirname() as /my_parent_folder/my_folder/my_file.txt, it will return the directory name as /my_parent_folder/my_folder.

Example Usage:

const path = require("path");

// Example path to a file
const filePath = "/my_parent_folder/my_folder/my_file.txt";

// Getting the directory name using path.dirname()
const directoryName = path.dirname(filePath);

// Output: /my_parent_folder/my_folder
console.log(directoryName);

Trailing Directory Separators:

The path.dirname() method ignores any trailing directory separators (like /) at the end of the path string. For example, if the given path is /my_parent_folder/my_folder/, it will still return /my_parent_folder/my_folder as the directory name.

Potential Applications:

  • Getting the parent directory path: Use this method to retrieve the path to the parent directory, which can be useful when navigating file systems or working with file directories.

  • Organizing files into directories: By extracting the directory name, you can organize files into their correct directories based on their path structure.

  • File path validation: You can check if a given file path is valid by ensuring that it has a valid directory name. If the path.dirname() method returns an empty string, the file path is likely invalid.


What is path.extname(path)?

The path.extname() method in Node.js's path module is used to get the extension of a file path. The extension is the part of the file name after the last period (.) character. For example, the extension of the file index.html is .html.

How to use path.extname(path)

To use the path.extname() method, you simply pass in the file path as a string. The method will return the extension of the file as a string.

const path = require("path");

const filePath = "/Users/username/Desktop/index.html";

const fileExtension = path.extname(filePath);

console.log(fileExtension); // '.html'

Potential applications in real world

The path.extname() method can be used in a variety of real-world applications, such as:

  • Determining the file type of a file.

  • Filtering files by their type.

  • Creating custom file extensions.

Real-world complete code implementations and examples

Here is a complete code implementation that demonstrates how to use the path.extname() method to determine the file type of a file:

const path = require("path");

const filePath = "/Users/username/Desktop/index.html";

const fileExtension = path.extname(filePath);

if (fileExtension === ".html") {
  console.log("This is an HTML file.");
} else if (fileExtension === ".js") {
  console.log("This is a JavaScript file.");
} else if (fileExtension === ".css") {
  console.log("This is a CSS file.");
} else {
  console.log("This is an unknown file type.");
}

Output:

This is an HTML file.

Simplified and detailed explanation in plain English

The path.extname() method in Node.js's path module is like a tool that helps you find out what kind of file you have. It looks at the file name and finds the part after the last period (.) character. That part is called the extension.

For example, if you have a file called index.html, the extension is .html. This tells you that the file is an HTML file.

You can use the path.extname() method to do things like:

  • Figure out if a file is an image, a video, or a document.

  • Sort files by their type.

  • Create custom file extensions for your own applications.

Here's a simple example of how you can use the path.extname() method:

const path = require("path");

const filePath = "/Users/username/Desktop/index.html";

const fileExtension = path.extname(filePath);

console.log(fileExtension); // '.html'

This code will print the file extension .html to the console.


What is the path.format() method?

In JavaScript, the path module provides a set of functions for working with file paths. The path.format() method is used to create a path string from an object.

The object you pass to path.format() must have the following properties:

  • dir: The directory part of the path.

  • root: The root part of the path.

  • base: The base part of the path.

  • name: The name part of the path.

  • ext: The extension part of the path.

The path.format() method will return a path string that is constructed from the values of the properties in the object.

How to use the path.format() method

The following code shows you how to use the path.format() method:

const path = require("path");

const pathObject = {
  dir: "/home/user/dir",
  root: "/",
  base: "file.txt",
  name: "file",
  ext: ".txt",
};

const pathString = path.format(pathObject);

console.log(pathString); // '/home/user/dir/file.txt'

In this example, the path.format() method returns the path string /home/user/dir/file.txt.

When to use the path.format() method

You can use the path.format() method to create a path string from an object that represents a file or directory. This can be useful in a variety of situations, such as:

  • When you need to create a path string for a file or directory that is stored in a database.

  • When you need to create a path string for a file or directory that is passed to a command-line tool.

  • When you need to create a path string for a file or directory that is used in a web application.

Real-world examples of the path.format() method

The following are some real-world examples of how the path.format() method can be used:

  • Creating a path string for a file that is stored in a database:

const path = require("path");

const pathObject = {
  dir: "/home/user/dir",
  root: "/",
  base: "file.txt",
  name: "file",
  ext: ".txt",
};

const pathString = path.format(pathObject);

// Store the path string in a database.
  • Creating a path string for a file that is passed to a command-line tool:

const path = require("path");

const pathObject = {
  dir: "/home/user/dir",
  root: "/",
  base: "file.txt",
  name: "file",
  ext: ".txt",
};

const pathString = path.format(pathObject);

// Pass the path string to a command-line tool.
  • Creating a path string for a file that is used in a web application:

const path = require("path");

const pathObject = {
  dir: "/home/user/dir",
  root: "/",
  base: "file.txt",
  name: "file",
  ext: ".txt",
};

const pathString = path.format(pathObject);

// Use the path string in a web application.

Simplified Explanation:

The path.isAbsolute() method in Node.js checks if a given path is an absolute path or a relative path.

Key Points:

  • Absolute Path: A path that starts with a root directory (e.g., / on POSIX systems, C:/ on Windows).

  • Relative Path: A path that starts with a relative directory (e.g., ./, ../).

How it Works:

  • The method takes a path as input and returns true if the path is absolute, otherwise false.

  • If the given path is an empty string, it returns false.

Real-World Example:

Consider the following:

path.isAbsolute('/Users/john/docs/file.txt'); // true
path.isAbsolute('./Projects/app.js'); // false

In the first example, the path /Users/john/docs/file.txt is absolute because it starts with the root directory /. In the second example, the path ./Projects/app.js is relative because it starts with the relative directory ./.

Applications:

  • Determining the full path to a file

  • Resolving paths for modules and other resources

  • Checking if a path is valid before using it in file operations

Code Implementation:

// Check if a path is absolute
const isAbsolute = path.isAbsolute("/Users/john");

// If the path is absolute, log it to the console
if (isAbsolute) {
  console.log(`The path is absolute: ${path}`);
}

path.join(...paths)

In simpler terms, path.join() is a function that takes a list of path pieces and combines them into a single, valid path.

Example:

path.join("home", "user", "Downloads");
// Returns: 'home/user/Downloads'

How it works:

Here's what happens behind the scenes:

  1. path.join() takes your path pieces and puts them together using the appropriate separator for your operating system (e.g., "/" for Windows, Mac, and Linux).

  2. It then simplifies the path by removing any unnecessary dots or empty directories. For example, it would turn ./foo/../bar into just bar.

Use Cases:

  • Constructing file paths: You can use path.join() to build file paths for reading or writing files.

  • Working with file systems: When you need to navigate through a file system, path.join() helps you build relative paths between directories.

  • Dynamic path generation: You can have code that generates paths based on varying input, and path.join() ensures that the paths are always valid.

Real-World Example:

Suppose you have a program that reads files from a specific directory. You could use path.join() to construct the path to the file like this:

const directory = "my_app_data";
const fileName = "data.txt";
const filePath = path.join(directory, fileName);

By using path.join(), you avoid potential issues with invalid or incorrect paths, ensuring that your program can access the file smoothly.


What is path.normalize()?

path.normalize() is a function in Node.js that "cleans up" a given path by removing unnecessary parts and making it more consistent.

How does it work?

path.normalize() takes a string representing a path (like a file or directory location) and does the following:

  1. Removes duplicate slashes: If there are multiple slashes (/) in a row, it replaces them with a single slash. For example, path.normalize('foo/bar///baz') would become 'foo/bar/baz'.

  2. Removes "dot" segments: If it finds any '.' segments in the path, it removes them. A '.' segment is a path component that refers to the current directory. For example, path.normalize('foo/bar/./baz') would become 'foo/bar/baz'.

  3. Removes "parent" segments: If it finds any '..' segments in the path, it removes them along with the previous path component. A '..' segment is a path component that refers to the parent directory. For example, path.normalize('foo/bar/../baz') would become 'foo/baz'.

Return Value:

path.normalize() returns a string representing the normalized path.

Example:

const path = require("path");

// Normalize a path
console.log(path.normalize("/foo/bar///baz/asdf/quux/..")); // '/foo/bar/baz/asdf'

Real-World Applications:

  • File handling: When working with files and directories, you often need to normalize paths to ensure they are consistent and unambiguous.

  • URL parsing: When parsing URLs, you can use path.normalize() to clean up the path component and make it more manageable.


path.parse(path)

  • path {string}

  • Returns: {Object}

The path.parse() method breaks down a file path into an object with its individual components:

  • dir: The directory part of the path, excluding the file name.

  • root: The root part of the path, which is the first part before any slashes (/ or \).

  • base: The base name of the file, including the file extension.

  • name: The name of the file without the extension.

  • ext: The extension of the file, including the dot (.).

Here's an example to make it clearer:

const path = require("path");

const filePath = "/home/user/dir/file.txt";

const parsedPath = path.parse(filePath);

console.log(parsedPath);

Output:

{ root: '/',
  dir: '/home/user/dir',
  base: 'file.txt',
  ext: '.txt',
  name: 'file' }

Real-World Applications

  • File Path Manipulation: You can use path.parse() to extract specific parts of a file path, making it easier to work with the path. For example, you could use it to:

    • Get the file name without the extension for display purposes.

    • Check if the file has a specific extension to determine its type.

    • Extract the directory path to create a new file or folder within that directory.

  • Path Validation: You can use path.parse() to validate a file path and ensure it has the correct components and structure.

  • Path Comparison: By comparing the parsed components of two paths, you can determine if they refer to the same file or directory.


What is path.posix?

The path.posix object in Node.js provides functions for manipulating file paths in a POSIX-compliant manner. POSIX is a set of standards for operating systems, and many systems like Unix, Linux, and macOS follow these standards.

Functions in path.posix:

  • posix.resolve(...): Combines multiple file paths into a single, absolute path. For example:

const resolvedPath = path.posix.resolve("/home/user", "documents", "file.txt");
// Result: '/home/user/documents/file.txt'
  • posix.normalize(...): Simplifies a file path by removing unnecessary parts, such as .. and .. For example:

const normalizedPath = path.posix.normalize("/home/user/../documents/file.txt");
// Result: '/home/documents/file.txt'
  • posix.isAbsolute(...): Checks if a file path is absolute. An absolute path starts with a root directory, like /. For example:

const isAbsolute = path.posix.isAbsolute("/home/user/file.txt");
// Result: true

const isRelative = path.posix.isAbsolute("file.txt");
// Result: false
  • posix.relative(...): Calculates the relative path between two paths. For example:

const relativePath = path.posix.relative(
  "/home/user/documents",
  "/home/user/file.txt"
);
// Result: '../file.txt'
  • posix.join(...): Combines multiple file paths into a single path. Unlike resolve, it does not resolve the path to an absolute one. For example:

const joinedPath = path.posix.join("/home/user", "documents", "file.txt");
// Result: '/home/user/documents/file.txt'
  • posix.parse(...): Parses a file path into its components: root, dir, basename, ext. For example:

const parsedPath = path.posix.parse("/home/user/documents/file.txt");
// Result:
// {
//   root: '/',
//   dir: '/home/user/documents',
//   base: 'file.txt',
//   ext: '.txt'
// }

Real-World Applications:

  • File Manipulation: Managing and navigating through files in a directory.

  • Path Resolution: Determining the absolute location of a file, even when provided with relative paths.

  • Path Manipulation: Creating relative paths, joining paths, and extracting file extensions.


Simplified Explanation

Imagine you're in your computer's file system, like a giant folder.

  • path.relative() helps you find the path from one folder to another.

  • from is the folder you're starting from.

  • to is the folder you want to go to.

Example

Let's say you're in the "Documents" folder and you want to go to the "Pictures" folder.

path.relative('Documents', 'Pictures');

This will return "Pictures" because the "Pictures" folder is directly inside the "Documents" folder.

Real-World Applications

  • Navigation: Path.relative is used in file browsers to show the relative path to the current folder from the root folder.

  • File Linking: If you want to link to a file in another folder, you can use path.relative to get the relative path instead of the absolute path.

  • Error Handling: When an error occurs while accessing a file, the error message might include the relative path to the file.

Code Implementations

// Get the relative path from "C:\Users\John\Desktop" to "C:\Users\John\Documents"
const relativePath = path.relative(
  "C:\\Users\\John\\Desktop",
  "C:\\Users\\John\\Documents"
);

console.log(relativePath); // "..\Documents"
// Get the relative path from "/home/user/Projects/Project1" to "/home/user/Projects/Project2"
const relativePath = path.relative(
  "/home/user/Projects/Project1",
  "/home/user/Projects/Project2"
);

console.log(relativePath); // "../Project2"

Potential Applications

  • Cross-platform compatibility: The relative path can be used consistently across different operating systems, as it does not depend on the specific file system structure.

  • Simplifying file operations: Using relative paths instead of absolute paths can simplify file operations, as it makes it easier to refer to files within a particular directory or project.

  • Improving performance: Relative paths can improve performance in certain scenarios, such as when working with large file systems or when the file system structure is frequently changing.


The path.resolve() method in Node.js is used to build an absolute path from a series of path segments.

An absolute path specifies the full location of a file or directory on your computer, starting from the root directory.

The path.resolve() method takes a sequence of paths or path segments as arguments and returns an absolute path.

The path segments are processed from right to left, with each subsequent segment prepended until an absolute path is constructed.

For example, given the sequence of path segments:

/foo
/bar
baz

Calling path.resolve('/foo', '/bar', 'baz') would return /bar/baz because 'baz' is not an absolute path but '/bar' + '/' + 'baz' is.

If, after processing all given path segments, an absolute path has not yet been generated, the current working directory is used.

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

Zero-length path segments are ignored.

If no path segments are passed, path.resolve() will return the absolute path of the current working directory.

Here are some examples of how to use the path.resolve() method:

path.resolve("/foo/bar", "./baz");
// Returns: '/foo/bar/baz'

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

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

Potential applications in real world:

The path.resolve() method can be used in a variety of applications, such as:

  • Building absolute paths for files and directories

  • Resolving relative paths to absolute paths

  • Normalizing paths

  • Removing trailing slashes from paths


path.sep

A path separator is a character that separates different parts of a file path. For example, on Windows, the path separator is the backslash character (\), while on Unix systems, it is the forward slash character (/).

The path.sep property of the path module in Node.js provides the platform-specific path segment separator. This means that it will return the correct path separator for the operating system that you are using.

For example, on Windows:

const path = require("path");

console.log(path.sep); // Output: \

On Unix systems:

const path = require("path");

console.log(path.sep); // Output: /

You can use the path.sep property to ensure that your file paths are always using the correct separator for the operating system that you are using. This is especially important when you are writing code that will be used on multiple platforms.

Here is a real-world example of how you can use the path.sep property:

const path = require("path");

const filePath = path.join("my", "directory", "file.txt");

console.log(filePath); // Output: my\directory\file.txt

In this example, we are using the path.join() method to join together the different parts of a file path. The path.sep property is used to ensure that the correct path separator is used for the current operating system.

Potential applications of the path.sep property include:

  • Writing code that will be used on multiple platforms

  • Ensuring that file paths are always using the correct separator for the current operating system

  • Parsing file paths to extract the different parts of the path


path.toNamespacedPath(path)

Windows-only: Converts a path to its namespace-prefixed equivalent.

On Windows systems, certain file paths can be prefixed with a namespace. This namespace serves as a logical grouping mechanism for files and directories. The toNamespacedPath() method can be used to convert a regular path to its namespace-prefixed equivalent.

For example, consider the following path:

C:\Users\John\Documents\myfile.txt

This path can be converted to its namespace-prefixed equivalent using the toNamespacedPath() method:

path.toNamespacedPath('C:\Users\John\Documents\myfile.txt')

The result of this conversion would be:

\\?\C:\Users\John\Documents\myfile.txt

The namespace prefix \\?\ indicates that the path is a namespace-prefixed path. This prefix is necessary for accessing certain file paths, such as those that contain special characters or those that are located on remote network shares.

Real-world applications:

  • Accessing files and directories on remote network shares.

  • Working with file paths that contain special characters.

  • Managing files and directories in a namespace-aware manner.

Code example:

const path = require('path');

const pathWithNamespace = path.toNamespacedPath('C:\\Users\\John\\Documents\\myfile.txt');

console.log(pathWithNamespace); // \\?\C:\Users\John\Documents\myfile.txt

path.win32

The path.win32 property provides access to Windows-specific implementations of the path methods.

The API is accessible via require('node:path').win32 or require('node:path/win32').

Methods

The following methods are available in path.win32:

  • path.win32.parse(path)

  • path.win32.format(pathObject)

  • path.win32.resolve(...paths)

  • path.win32.normalize(path)

  • path.win32.isAbsolute(path)

  • path.win32.join(...paths)

  • path.win32.relative(from, to)

  • path.win32.toNamespacedPath(path)

  • path.win32.dirname(path)

  • path.win32.basename(path)

  • path.win32.extname(path)

Examples

Parsing a Windows path

const path = require('node:path');
const win32Path = path.win32.parse('C:\\Users\\John\\Documents\\myfile.txt');

console.log(win32Path);
// {
//   root: 'C:\\',
//   dir: 'C:\\Users\\John\\Documents',
//   base: 'myfile.txt',
//   ext: '.txt',
//   name: 'myfile'
// }

Formatting a Windows path

const path = require('node:path');
const win32Path = path.win32.format({
  root: 'C:\\',
  dir: 'C:\\Users\\John\\Documents',
  base: 'myfile.txt',
  ext: '.txt',
  name: 'myfile'
});

console.log(win32Path);
// C:\Users\John\Documents\myfile.txt

Resolving Windows paths

const path = require('node:path');
const win32Path = path.win32.resolve('C:\\Users\\John', 'Documents', 'myfile.txt');

console.log(win32Path);
// C:\Users\John\Documents\myfile.txt

Normalizing Windows paths

const path = require('node:path');
const win32Path = path.win32.normalize('C:\\Users\\John\\..\\Documents\\myfile.txt');

console.log(win32Path);
// C:\Users\Documents\myfile.txt

Checking if a Windows path is absolute

const path = require('node:path');
const isAbsolute = path.win32.isAbsolute('C:\\Users\\John\\Documents\\myfile.txt');

console.log(isAbsolute);
// true

Joining Windows paths

const path = require('node:path');
const win32Path = path.win32.join('C:\\Users\\John', 'Documents', 'myfile.txt');

console.log(win32Path);
// C:\Users\John\Documents\myfile.txt

Getting the relative path between two Windows paths

const path = require('node:path');
const win32Path = path.win32.relative('C:\\Users\\John\\Documents', 'C:\\Users\\John\\Documents\\myfile.txt');

console.log(win32Path);
// myfile.txt

Converting a Windows path to a namespaced path

const path = require('node:path');
const win32Path = path.win32.toNamespacedPath('C:\\Users\\John\\Documents\\myfile.txt');

console.log(win32Path);
// \\?\C:\Users\John\Documents\myfile.txt

Getting the directory name of a Windows path

const path = require('node:path');
const win32Path = path.win32.dirname('C:\\Users\\John\\Documents\\myfile.txt');

console.log(win32Path);
// C:\Users\John\Documents

Getting the base name of a Windows path

const path = require('node:path');
const win32Path = path.win32.basename('C:\\Users\\John\\Documents\\myfile.txt');

console.log(win32Path);
// myfile.txt

Getting the extension of a Windows path

const path = require('node:path');
const win32Path = path.win32.extname('C:\\Users\\John\\Documents\\myfile.txt');

console.log(win32Path);
// .txt