The previous article explained what OS module is and how it can be used to get information regarding the underlying OS. In this article we are going to study node.js path module which is yet another extremely handy module when it comes to performing path related operations
The previous article explained what OS module is and how it can be used to get information regarding the underlying OS. In this article we are going to study node.js path module which is yet another extremely handy module when it comes to performing path related operations such a resolving a relative path to its absolute path, checking whether a path is absolute or not, joining multiple path, getting directory name from path and finding file extensions. Following are some of the most useful functions in node.js path module.
To see all the path functions discussed above in action, take a look at the following example. Create a file named pathmodule.js and add the following code to the file.
var pathmod = require("path"); console.log('Normalization funcion :'+ pathmod.normalize('/path/path2//path2slashes/path3/tab/..')); console.log('Join Path Funcion :'+ pathmod.join('/path1', 'path2', 'newpath/path3', '..')); console.log('Resolve Function :'+ pathmod.resolve('pathmodule.js')); console.log('Extension name function :'+ pathmod.extname('mainmodule.js'));
Take a careful look at the above code. Your results might be different depending upon the path values that you have used. However, the first function simply returns the normalize path without double slashes and dots etc. The function joins all the paths passed to it and returns a single path. The resolve function returns the absolute path of the file “pathmodule.js”. Similarly the last function i.e. extname returns the extension of the file “pathmodule.js” i.e. “js”.