Node.JS Path Module

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.

  1. path.normalize(p): This function normalizes the path passed as parameter by taking care of . and .. etc.
  2. path.join(p1,p2,p3 …): This function joins all the paths passed to it as a parameter and returns the normalized joint path.
  3. path.resolve(p): It resolves the path any path passed as parameter to its complete absolute path.
  4. path.isAbsolute(p): Returns true if the path passed to the function is an absolute path.
  5. path.extname(p): This function returns the extension name of the file in the last part of the path. If the file doesnt contain a “.” then the function cannot calculate the file name. Rather it returns an empty string.

Node.js Path Module Example

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'));

Download the code Try the code

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”.

<<< Node.JS OS ModuleNode.JS Child Process Creation >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .