Path Module in Node.JS

Path Module in Node.JS

The path module is one of several Node js modules that make our lives as developers easier. In my opinion, the route module is one of the most misunderstood modules in nodejs, and today I will try to explain what the most commonly used path module methods are, and how to use them in your project.

Why use Path Module?

First of all, we will discuss why we need the 'Path Module' in NodeJS. As we all know, while working with backend systems or performing API calls, we frequently need the path to a file or folder structure for a variety of purposes. These file paths differ across operating systems. For example, in Windows, the file path begins with "C:" or "D:", whereas in Linux and MacOS, the directory begins with root. Along with this issue, in Windows, we use "\" to write the path of a file; in Linux and MacOS, we use '/'. Similarly, Windows uses ';' as its delimeter, whereas Linux and MacOS use ':' as its delimeter. As we can see, if we don't have the path module, writing a path based on different operating systems will be an absolute pain.

Details of a file path

A file path has the above architecture, it is mainly composed of two main things, which are 'directory' and 'base'. The base is subdivided into the 'name' of the file along with its 'extension'. Whereas the directory contains the parent path and the 'root'. We can see that there is a difference between the delimiters used in different operating systems, like '\' in Windows and '/' in Linux and MacOS.

Important Methods of Path Module

For using the path module of the NodeJS, we need to import the path module to the package in which we are working. For doing so, we can import the path module either by commonJS module (require syntax) or by ES module (import syntax), both of these syntaxes are as follows:

// for commonJS module
const path = require('path');

// for ES module
import path from 'path';

The important methods of the path module of NodeJS are as follows:

Let us suppose the filepath be ("/home/kartikd/Documents/Node Rev/NodePathModule/index.js"), we will assume it to be constant in all of the following examples:

  • Basic Commands:
    1. "__filename" : it returns the filepath of the current file. (note: it is not always available, checkout it's alternatives in "ES modules")
    2. "path.sep" : it returns the separator which the OS uses for returning the path. (returns '/' in Linux and MacOS and '\' in Windows).

       console.log("Separator -> ", path.sep) // '/' in mac and linux 
      //and '\' in windows
    
    1. "path.delimeter()" : it returns the delimiter used in the specific operating system.
    console.log('delimeter in this OS -> ',path.delimiter)
    //for linux/mac delimeter is ':' while in windows, 
    //the delimeter is ';'
  • "path.basename()" : it returns the basename of the provided file path.

      console.log('basename -> ', path.basename(__filename)); 
      //output: basename ->  index.js
      //return the basename of the directory
    
      //for printing the filename without the extension, we can use the following syntax:
      console.log("basename without extension name -> ", path.basename(__filename, '.js'))
      //output: name ->  index
    
  • "path.dirname()" : returns the directory name of the file path.

      console.log('dirname -> ', path.dirname(__filename))
      //output : dirname ->  /home/kartikd/Documents/Node Rev/NodePathModule
    
  • "path.extname()" : returns the file extension.

      console.log(('ext name ->' ), path.extname(__filename))
      //output: ext name -> .js
    
  • "path.format()" : it is used for creating the path addresses based on the directory and base addresses.

const pathToFile = path.format({
    dir: '/home/kartikd/Documents/Node Rev/NodePathModule',
    base: 'index.html'
})
console.log(pathToFile)
//output : /home/kartikd/Documents/Node Rev/NodePathModule/index.html
//here we are creating the path of index.html file by using the 
// path.format method
  • "path.isAbsolute()" : checks that the path provided is an absolute path or a relative path (returns a boolean value)
console.log("__filename -> ", path.isAbsolute(__filename))
//output : __filename ->  true
console.log("/etx/config/abc -> ", path.isAbsolute("/etx/config/abc"))
//output : /etx/config/abc ->  true
console.log("./index.js -> ", path.isAbsolute("./index.js"))
//output : ./index.js ->  false
console.log("../js/index.js -> ", path.isAbsolute("../js/index.js"))
//output : ../js/index.js ->  false
  • "path.join()" : it is used to join multiple parsed fragments of a file path. it automatically connects all the paths with a relevant delimiter.
console.log('join -> ', path.join('/home', 'js', 'dist', 'app.js'))
//output : join ->  /home/js/dist/app.js
  • "path.parse()" : segregates the path address into an object containing the base, name, extention, root and directory of the path inputted
console.log("parse -> ", path.parse(__filename))
/* output : parse ->  {
                  root: '/',
                  dir: '/home/kartikd/Documents/Node Rev/NodePathModule',
                  base: 'index.js',
                  ext: '.js',
                  name: 'index'
            }
*/
  • "path. relative()" : it takes two arguments as an input which refer to the from and to paths. This function returns the path which directs from the 'from' directory to the 'to' directory.
console.log("relative -> " , path.relative('from', 'to'))
//output : relative ->  ../to
console.log("relative -> " , path.relative('/home/user/desktop/web-apps/react/first', '/home/user/desktop/web-apps/react/second'))
//output : relative ->  ../second
console.log("relative -> " , path.relative('/home/user/desktop/web-apps/react/first', '/home/user/desktop/web-apps/angular/first'))
//output : relative ->  ../../angular/first
console.log("relative -> " , path.relative('/home/user/desktop/web-apps/react/first', '/home/user/desktop/mob-apps/vue/first'))
//output : relative ->  ../../../mob-apps/vue/first
  • "path.normalize()" : it returns the normalizes file path.
console.log(path.normalize("//home//user//main//files//index.js"))
//output : /home/user/main/files/index.js
console.log(path.normalize("//home/user//main//files//index.js"))
//output : /home/user/main/files/index.js
  • "path.resolve()" : explore!