Path Module
Path Module
Path Module
List of content:
NodeJS path module
The path module has many useful properties and methods to access and manipulate paths in the file system.
The path is a core module in Node. Therefore, you can use it without installing:
The path object has the sep property that represents the platform-specific path separator:
The path object also has the delimiter property that represents the path delimiter:
The following shows some handy methods of the path module that you probably use very often:
The path.basename() returns the last portion of a specified path. For example:
Output:
The ext parameter filters out the extension from the path:
Output:
path.dirname(path)
The path.dirname() method returns the directory name of a specified path. For example:
Output:
Output:
The path.format() method returns a path string from a specified path object.
path.isAbsolute(path)
For example:
path.parse(path)
The path.parse() method returns an object whose properties represent the path elements. The returned object
has the following properties
On Linux or macOS:
Output:
path.normalize(path)
The path.normalize() method normalizes a specified path. It also resolves the '..' and '.' segments.
Output:
path.relative(from, to)
The path.relative() accepts two arguments and returns the relative path between them based on the current
working directory.
path.resolve(…paths)
The path.resolve() method accepts a sequence of paths or path segments and resolves it into an absolute
path. The path.resolve() method prepends each subsequent path from right to left until it completes
constructing an absolute path.
If you don’t pass any argument into the path.resolve() method, it will return the current working directory.
Output:
In this example, the path.resolve() method returns a path that is the same as the current working directory.