The path module in Node.js is a built-in module that provides utilities for working with file and directory paths. It helps in constructing, manipulating, and working with file and directory paths in a cross-platform manner, making it easier to write platform-independent code.
Here are some common functions provided by the path module:
Joins one or more path segments into a single path, using the appropriate platform-specific separator (e.g., "\" on Windows and "/" on Unix-like systems).
Resolves an absolute path from relative paths. It returns an absolute path by combining the current working directory with the provided paths.
const path = require('path'); const absolutePath = path.resolve('folder', 'file.txt');
3. path.basename(path, [ext]):
Returns the last portion of a path (i.e., the filename). You can also specify an extension to remove.
const path = require('path'); const filename = path.basename('/path/to/file.txt'); // Returns 'file.txt'
Returns the directory name of a path.
const path = require('path'); const dirname = path.dirname('/path/to/file.txt'); // Returns '/path/to'
Returns the file extension of a path, including the dot.
const path = require('path'); const extension = path.extname('/path/to/file.txt'); // Returns '.txt'
Normalizes a path by resolving '..' and '.' segments and removing redundant slashes.
const path = require('path'); const normalizedPath = path.normalize('/path/to/../file.txt'); // Returns '/path/file.txt'
Check if a path is an absolute path.
const path = require('path'); const isAbsolute = path.isAbsolute('/path/to/file.txt'); // Returns true
These are just a few of the functions provided by the path module. The module is particularly useful when dealing with file I/O, working with file paths in a cross-platform way, and ensuring that your code behaves consistently across different operating systems.