DEV Community

Cover image for Node.js path module
Ujjawal Kumar
Ujjawal Kumar

Posted on

Node.js path module

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).


Enter fullscreen mode Exit fullscreen mode

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');

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

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'

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
pshaddel profile image
Poorshad Shaddel

Nice article.

Collapse
 
endeavourmonk profile image
Ujjawal Kumar

thanks πŸ™