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:
1. path.join([...paths]):
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).
2. path.resolve([...paths]):
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'
4. path.dirname(path):
Returns the directory name of a path.
const path = require('path');
const dirname = path.dirname('/path/to/file.txt'); // Returns '/path/to'
5. path.extname(path):
Returns the file extension of a path, including the dot.
const path = require('path');
const extension = path.extname('/path/to/file.txt'); // Returns '.txt'
6. path.normalize(path):
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'
7. path.isAbsolute(path):
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.
Top comments (2)
Nice article.
thanks 🙏