Working with paths in node.js is something that comes up all the time when it comes to file system related tasks. When doing so there is a desire for a nice framework to help with joining paths together, and help with problems that have to do with the differences of how paths are handled in windows and linux systems, along with many other common path related tasks. So I could look for some kind of npm package, write my own code.However for starters there is no need to bother with an npm package of any kind, or write my own code, as the node.js built in path module can help with a great deal of these kinds of tasks when working with a file system.
This is a task that I use the path module for all the time. I have a base path to a working folder or any kind of folder or interest where there are resources of some kind. I then also have a relative path from that working path and I want to create a path from the base path and the relative path. One way to go about doing so with the path module in nodejs is to use the path join method.
In the above example I am using the posix property of the path module to make sure that I end up getting a posix rather than win32 friendly path result. I could just call path.join but that would give a result that is different depending on the underlaying operating system that node is running on. In some situations I might want to do something that way actually but for this example I wanted to make a simple code example of the path join method that will return the same result on any kind of platform.
So another node path method module method that I use a lot is the resolve method. This also works like path join but will resolve the path to an abolsute path.
Another task that is quickly solved with the path module is getting the base name of a path. This is helpful for getting a filename from the end of a path.
Opposite of basename is path.dirname.
I often end up in situations in which I have many different path parts and I want to piece them together into a single path in a way in which it will always come together in a single valid path. The join method serves me well with this.
An absolute path is a full path all the way back to root. On a posix system an absolute path is something like this
On a windows system it would be something like this
This differs from a relative path like this
As such it is nice to have a way to find out if a path is absolute or not, so there is a method for that called path.isAbsolute.
I recently ran into a situation in which I need to find out if a path is a sub dir of another path in order to exclude it if it is. Path.relative comes in handy with this.