Node.js path Module

Java FileNode.js built-in modules


Node.js'spathThe module is a built-in core module, specifically designed to handle file and directory paths.

path provides a series of practical methods that allow you to safely and efficiently manipulate file paths in different operating system environments.

Why do you need the path module?

Different operating systems use different path separators:

  • Windows uses backslashes\
  • Unix/Linux/macOS use forward slashes/

pathThe module automatically handles these differences, allowing your code to work properly on different platforms.


Basic usage of the path module

Importing the path module

const path = require('path');

Common methods

1. path.join([...paths]) - Join paths

Example

const fullPath = path.join('/user', 'documents', 'file.txt');
console.log(fullPath);
// On Unix, outputs: /user/documents/file.txt
// On Windows, outputs: \user\documents\file.txt

2. path.resolve([...paths]) - Resolve an absolute path

Example

const absolutePath = path.resolve('src', 'app.js');
console.log(absolutePath);
// Outputs the absolute path in the current working directory, e.g.: /home/user/project/src/app.js

3. path.basename(path[, ext]) - Get the file name

Example

console.log(path.basename('/user/docs/file.txt')); // file.txt
console.log(path.basename('/user/docs/file.txt', '.txt')); // file

4. path.dirname(path) - Get the directory name

Example

console.log(path.dirname('/user/docs/file.txt')); // /user/docs

5. path.extname(path) - Get the file extension

Example

console.log(path.extname('index.html')); // .html
console.log(path.extname('file')); // Empty string

Cross-platform path handling

Path separators

  • path.sep- Platform-specific path separator

    console.log(path.sep); // Windows 输出 '\', Unix 输出 '/'
  • path.delimiter- Platform-specific path separator (used in the PATH environment variable)

    console.log(path.delimiter); // Windows 输出 ';', Unix 输出 ':'

Path normalization

Usingpath.normalize(path)can normalize paths, handling redundant.、..and separators:

Example

console.log(path.normalize('/user//docs/../file.txt')); // /user/file.txt

Path parsing and format conversion

path.parse(path) - Parse a path into an object

Example

const pathObj = path.parse('/user/docs/file.txt');
console.log(pathObj);
/*
{
  root: '/',
  dir: '/user/docs',
  base: 'file.txt',
  ext: '.txt',
  name: 'file'
}
*/

path.format(pathObject) - Build a path from an object

Example

const pathStr = path.format({
  dir: '/user/docs',
  name: 'file',
  ext: '.txt'
});
console.log(pathStr); // /user/docs/file.txt

Practical application examples

Example 1: Building cross-platform file paths

Example

const configPath = path.join(__dirname, 'config', 'settings.json');
console.log(configPath);

Example 2: Handling user-uploaded files

Example

function saveUploadedFile(uploadDir, originalName) {
  const ext = path.extname(originalName);
  const baseName = path.basename(originalName, ext);
  const timestamp = Date.now();
  const newFileName = `${baseName}_${timestamp}${ext}`;
 
  return path.join(uploadDir, newFileName);
}

Example 3: Checking file extensions

Example

function isImageFile(filename) {
  const ext = path.extname(filename).toLowerCase();
  return ['.jpg', '.jpeg', '.png', '.gif'].includes(ext);
}

Methods and properties

The methods and properties of the path module are as follows:

MethodDescriptionExample
path.basename(path[, ext])Returns the last part of the path (file name). The optional parameterextis used to remove the file extension.path.basename('/foo/bar/baz.txt'); // 输出: 'baz.txt'
path.dirname(path)Returns the directory part of the path.path.dirname('/foo/bar/baz.txt'); // 输出: '/foo/bar'
path.extname(path)Returns the file extension of the path.path.extname('/foo/bar/baz.txt'); // 输出: '.txt'
path.join([...paths])Joins multiple paths into one path, automatically handling path separators.path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); // 输出: '/foo/bar/baz/asdf'
path.resolve([...paths])Resolves a sequence of paths into an absolute path, processing each path segment from right to left until an absolute path is constructed.path.resolve('/foo/bar', './baz'); // 输出: '/foo/bar/baz'
path.normalize(path)Normalizes the path, removing redundant.and.., and replaces path separators according to the current operating system.path.normalize('/foo/bar//baz/asdf/quux/..'); // 输出: '/foo/bar/baz/asdf'
path.isAbsolute(path)Checks whether the path is an absolute path.path.isAbsolute('/foo/bar'); // 输出: true
path.relative(from, to)Returns fromfromthe path totothe relative path of the path.path.relative('/foo/bar/baz', '/foo/bar/qux'); // 输出: '../qux'
path.parse(path)properties.root、dir、base、extandnameFormats the path object into a path string, which ispath.parse('/home/user/dir/file.txt');the opposite.{ root: '/', dir: '/home/user/dir', base: 'file.txt', ...}
path.format(pathObject)Provides the path separator of the current operating system (POSIX ispath.parse, Windows ispath.format({ root: '/', dir: '/home/user/dir', base: 'file.txt' }); // 输出: '/home/user/dir/file.txt'
path.sepProvides the path delimiter (the separator between paths in environment variables), POSIX is'/', Windows is'\')。console.log(path.sep); // 输出: '\' (Windows) 或 '/' (POSIX)
path.delimiterExample:Example;。console.log(path.delimiter); // 输出: ';' (Windows) 或 ':' (POSIX)

Example

Create a main.js file, the code is as follows:

Example

const path = require('path');

// Get the file name
console.log('File name:', path.basename('/foo/bar/baz.txt')); // Outputs: 'baz.txt'

// Get the directory name
console.log('Directory name:', path.dirname('/foo/bar/baz.txt')); // Outputs: '/foo/bar'

// Get the extension
console.log('Extension:', path.extname('/foo/bar/baz.txt')); // Outputs: '.txt'

// Join paths
console.log('Joined path:', path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')); // Outputs: '/foo/bar/baz/asdf'

// Resolve absolute path
console.log('Absolute path:', path.resolve('/foo/bar', './baz')); // Outputs: '/foo/bar/baz'

// Normalize path
console.log('Normalized path:', path.normalize('/foo/bar//baz/asdf/quux/..')); // Outputs: '/foo/bar/baz/asdf'

// Determine whether it is an absolute path
console.log('Is absolute path:', path.isAbsolute('/foo/bar')); // Outputs: true

// Relative path
console.log('Relative path:', path.relative('/foo/bar/baz', '/foo/bar/qux')); // Outputs: '../qux'

// Parse path into object
const parsedPath = path.parse('/home/user/dir/file.txt');
console.log('Parsed path object:', parsedPath);
// Outputs: { root: '/', dir: '/home/user/dir', base: 'file.txt', ext: '.txt', name: 'file' }

// Format object as path
const formattedPath = path.format(parsedPath);
console.log('Formatted path:', formattedPath); // Outputs: '/home/user/dir/file.txt'

Java FileNode.js built-in modules

Other extensions