Path Module in Node JS
Overview
Node.js has become quite popular since its first release in 2009. Node.js offers asynchronous and event-driven architecture, but the most important are the core modules of Node.js. Node.js has many modules that make the life of a developer easier, and among those, one is a path module in node js, which is very efficient and useful in providing us with methods to access and manipulate paths in the file system. In general, Path modules help in making file path systems independent of any system environment.
Pre-requisites
There are no major pre-requisite for using path modules in Node.js. You just need to have an LTS (long-term support) or the latest version of Node.js installed in your current system. Being a part of core modules in Node.js, you do not need to install the path from any external source or use npm; you can just require the path module in node js.
Syntax :
Introduction to Node.js Path Module
Many people forget about one of Node.js' most simple and important core modules, the path module. The path module in node js is used for managing and altering file paths. It's a part of the core modules with methods that help you deal with directory and file path names on the local machine's file system. Every system has a different environment and a specific operating system to manage it. Different operating systems manage file and directory-related operations differently.
For example,
In Linux, the path of the file is represented using '/' between the directories. In Windows, the path of the file is represented by using '\' between the directories. In Macro, the path of the file is represented by using '\' as well as '/' between the directories.
LINUX: home/scaler/topics/file.txt
WINDOWS: C:\\user\scaler\topics\file.txt
MACRO: C:\user\scaler\topics\Img/nodejs.svg
In order to make these file and directory paths platform independent, Node.js has a module called path module. There are many important and useful functions inside the path module for handling the path of the file or the directory while developing a project. So let’s understand those important functions in the path module in node js one by one.
Syntax
The syntax of requiring the path module in any Node.js project is quite easy and straightforward.
Example:
Create a file main.js with the following code
Running the above file using the command below
Output:
Methods of Node.js Path Module
Let's discuss the methods of the path module in node js one by one :
Node.js path.basename() method:
The path.basename method is used to get the trailing part of the filename. The trailing directory separators are omitted when using this method. In layman’s terms, it returns either the name of the directory or a file that the file path refers to.
Syntax:
Description of the parameters: This method excepts two parameters which is as follows.
- path : <string> This is the file path or directory path that would be used to extract the filename.
- ext : <string> This is an optional parameter that is used to remove the file extension of the specified file.
- Return value: <string> This method returns the filename of the specified file string. It throws a TypeError if the, if the file path is not a string value or the extension, is given and is not a string value.
Example:
Let’s say we want to know the name of an image, and we passed the whole file path in a form of a string.
Output:
Now suppose we want to remove the extension of the filename, then
Output :
Although windows generally treat the file names and their extension in a case-insensitive manner, path.basename does not. For example, in windows C:\\filename.html and C:\\filename.HTML refer to the same file, but path.basename treats the extension as a case-sensitive string:
Node.js path.dirname() Method
The path.dirname method is used to get the directory name in which a particular file is present. This method is useful when we want to know the lowest directory name but have a full path name that leads to a file that is inside a directory. The path.dirname method ignores the trailing directory separators.
Syntax:
Description of the parameters: This method excepts two parameters which is as follows.
- path : <string> This method accepts a single parameter that is the file path name of a particular file whose directory is to be known.
- Return value: <string> This method returns the lowest directory name of the specified file string. It throws an TypeError if the file path is not a string value.
Example:
Let’s say we want to know the directory name in which an image is present, and we were passed the whole file path in a form of a string.
Output:
Node.js path.extname() Method
The path.extname method is used to get the extension of the specified file in the file path string. It extracts the file extension from the last occurrence of the period (.) character to the end of the file path string. If there is no period (.) character in the files path, then an empty string is returned.
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- path : <string> This method accepts a single parameter that is the file path of a particular file whose extension is to be known.
- Return value: <string> This method returns the extension of the specified file in the filepath. It throws a TypeError if the file path is not a string value.
Example :
Output:
Node.js path.format() Method
The path.format method is used to get the path string from the given path object. The path.format method receives pathObject, which is the combination of many properties in which one property may have priority over another property. A few priority orders are as follows:
- The pathObject.ext and pathObject.name parameter of the path object is ignored if the pathObject.base parameter is provided in the Object.
- .The pathObject.root parameter of the path Object is ignored if the pathObject.dir parameter is provided in the Object.
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- pathObject : <Object> Any JavaScript object having the following properties:
- dir : <string> This specifies the directory name of the path Object.
- root : <string> This specifies the root of the path Object.
- base : <string> This specifies the base of the path Object.
- name : <string> This specifies the name of the path Object.
- ext : <string> This specifies the file extension of the path Object.
- Return value : This method returns the path string from the provided path Object. It is basically the opposite of the path.parse
Example :
On POSIX,
Output:
On Windows,
Output :
Node.js path.isAbsolute() method:
The path.isAbsolute method is used to check if the specified path is an absolute path or not. An absolute path is described as a path that includes the entire details needed to locate a file.
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- path : <string> This method accepts a single parameter that is the file path of a specified file that would be used to check if the input path is absolute or not.
- Return value : <bool> This method returns a true or false value indicating if the path is an absolute path or not. It throws a TypeError if the file path is not a string value. It also returns a false value if the length of the file path is zero.
Example:
On POSIX,
Output:
On Windows,
Output :
Node.js path.join() Method
The method, path.join is used to join two, three, or a number of path segments into a single path using a particular platform-specific delimiter. The path segments which are to be joined are defined using comma-separated values. Normalization takes place after the joining of all the paths. The resultant string can be used anywhere as required. If the length of any of the path segments provided in the input is zero, then those path segments are ignored. If the resultant path formed by joining path-segments strings is of length zero, then (.) will be returned as the resultant, which denotes the current working directory.
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- path: <string> This method accepts parameters that are the comma separated file paths that are to be joined.
- Return value: <string> This method returns the string (file path) after joining all the comma-separated paths and normalizing it. It throws a TypeError if any of the comma-separated file paths is not a string value.
Example:
Output:
Node.js path.normalize() Method
The method, path.normalize() is used to obtain the normalised result from the given path. The path.normalize() method normalizes the given path, resolving the .. and . segments in their correct and readable form. If the method encounters multiple path segment separation characters (/, \, //, \\), then all are replaced by a single instance of the platform-specific path segment separator. The path.normalize() method preserves all trailing separators and is able to handle even the most complicated paths.
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- path: <string> This method accepts a single parameter that is the file path that is to be normalized.
- Return value: <string> This method returns the string (file path) after normalizing it. It throws a TypeError if the file path is not a string value.
Example:
Output:
Node.js path.parse() Method
The values of these properties may be different for every platform. It ignores the platform’s trailing directory separators during parsing. The path.parse returns the object which has the following properties:
- dir : <string> directory name
- root : <string> root name
- base : <string> file name with extension
- name : <string> only file name
- ext : <string> only extension name
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- path: <string> This method accepts a single parameter that is the file path that is to be parsed.
- Return value : <string> This method returns an object after parsing the file path. It throws a TypeError if the file path is not a string value.
Example:
On POSFIX,
Output:
Node.js path.relative() Method
The method, path.relative is used to get the relative path from a given path to another path based on the present working directory. If a zero-length string is passed in the parameters from or to then the present working directory is used, instead of the zero-length string. If both the parameter that is from and to are the same then a zero-length string is returned.
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- from <string> This is the file path that iwill be used as the base path.
- to <string> This is the file path that will be used to find the relative path.
- Return value: <string> This method returns a string in a normalized form. It throws a TypeError if the parameters from or to are not a string value.
Example:
Output:
Node.js path.resolve() Method
The method path.resolve is used to get the absolute path of any file. It is used to resolve any series of path segments. This method parses the paths from the right-hand side to the left-hand side, prepending each path until the resultant absolute path is constructed. The resultant absolute path is normalized, and all the following slashes are removed as needed. If zero path segments are provided in the parameters, then the absolute path of the present working directory is used. Zero-length paths are ignored by this method.
Syntax:
Description of the parameters: This method excepts two parameter which are as follows.
- path: <string> This method accepts a sequence of paths that would be resolved to construct an absolute path.
- Return value : <string> This method returns the absolute constructed path. It throws a TypeError if the file path is not a string value.
Example:
Output:
Node.js path.toNamespacedPath() Method
The method path.toNamespacedPath is used to find the equivalent namespace-prefixed path from the given input path. The path.toNamespacedPath method just works on the Windows systems as it is non-operational on the POSIX systems.On POSTIX systems it just returns the same path without modification. If the path is not a string, the path would be returned without modification.
Syntax:
Description of the parameters: This method excepts two parameters which are as follows.
- path: <string> This method accepts a path that is to convert.
- Return value: <string> This method returns the string with equivalent namespace-prefixed path.
Example:
Output:
All the methods of path modules in node js in brief:
Method | Description |
---|---|
basename() | This method returns the trailing part of the file name |
delimiter | This method returns the specified delimiter for a platform |
dirname() | This method returns the lowest directories of a path name |
extname() | This method returns the file extension of a path name |
format() | This method formats a path name object into a path name string |
isAbsolute() | This method returns true if a path name is an absolute path name, otherwise this method returns false |
join() | This method joins the specified comma separated path names into one path |
normalize() | This method normalizes the specified path name |
parse() | This method formats a path name string into a path name object |
posix | This method returns an object containing POSIX specific properties and methods |
relative() | This method returns the relative path name from one specified path name to another specified path name |
resolve() | This method resolves the specified path names into an absolute path name |
sep | This method returns the segment separator specified for the platform |
win32 | This method returns an object containing Windows specific properties and methods |
Ready to create blazing-fast applications? Enroll in our Free Node JS certification course and learn to optimize your web projects for speed.
Conclusion
- Node.js is an open-source, cross-platform Javascript runtime environment that runs on chrome's V8 engine internally.
- Node.js core module contains a path module, which is used to interact with file paths present in your system.
- Path module in node js makes the file path system independent of any system environment.
- Path module is a part of core modules in Node.js hence we do not need to download it from any external resource like npm (Node package manager).
- Path module can be used in a project by just requiring it. const path = require('path');
- Generally, the Path modules in Node.js provide methods that take only string parameters and throw a TypeError if parameters are not a string.
- Path module in node js contains many import methods, some of the are dirname(), join(), extname(), basename(), and normalize() that are explained above.
- Path module also contains path.toNamespacedPath() method which only works in windows environment.