Node File Paths - Manipulating and Interacting with Paths in Node
In Node, working with file paths is essential for many applications. However, there are differences between file paths on different operating systems that must be taken into account. In this article, we will explore how to interact with and manipulate file paths in Node.
Getting information out of a path
To extract information from a file path, Node provides several useful methods:
dirname
: Returns the parent folder of a file.basename
: Returns the filename part of a path.extname
: Returns the file extension.
Here’s an example of how to use these methods:
1 | const path = require('path'); |
By providing a second argument to basename
, you can get the file name without the extension:
1 | path.basename(filePath, path.extname(filePath)); // Returns: notes |
Working with paths
Node provides the path.join()
method to join multiple parts of a path:
1 | const path = require('path'); |
To obtain the absolute path calculation of a relative path, you can use the path.resolve()
method:
1 | const path = require('path'); |
If you provide a second parameter to resolve
, it will use the first parameter as the base for the second:
1 | const path = require('path'); |
If the first parameter starts with a slash, it denotes an absolute path:
1 | const path = require('path'); |
Another useful function provided by Node is path.normalize()
, which attempts to calculate the actual path when it contains relative specifiers like .
or ..
, or double slashes:
1 | const path = require('path'); |
It is important to note that both resolve
and normalize
do not check if the path exists; they simply perform calculations based on the given information.
Tags: Node.js, file paths, path manipulation, path joining, path normalization, basename, dirname, extname