Path Module in Node Js

  • The `path` module in Node.js provides utilities for working with file and directory paths. It is a core module, so there's no need to install it separately. The primary purpose of the `path` module is to handle file and directory paths in a platform-independent manner, making it easier to write cross-platform code.
Here are some key functions provided by the `path` module, along with examples:
  • Joining Path Segments: path.join(...paths) This method joins all the path segments together using the platform-specific separator.


    const path = require('path');

    const fullPath = path.join('/home', 'user', 'documents', 'file.txt');
    console.log(fullPath);  //  \home\user\documents\file.txt

  • Normalize Path: path.normalize(path) This method normalizes the given path, resolving '..' and '.' segments.


    const path = require('path');

    const normalizedPath = path.normalize('/home/user/../documents/./file.txt');
    console.log(normalizedPath);  //  \home\documents\file.txt

  • Resolve Path: path.resolve(...paths) This method resolves an absolute path from relative paths. It returns the absolute path to the given location.


    const path = require('path');

    const absolutePath = path.resolve('folder', 'file.txt');
    console.log(absolutePath);
    //  C:\Users\gagan\OneDrive\Desktop\Code\javascript\folder\file.txt

  • Get Directory Name: path.dirname(path) This method returns the directory name of a path.


    const path = require('path');

    const dirName = path.dirname('/home/user/documents/file.txt');
    console.log(dirName);   //  /home/user/documents

  • Get File Name: path.basename(path, [ext]) This method returns the last portion of a path. The second optional argument can be used to exclude a file extension.


    const path = require('path');

    const fileName = path.basename('/home/user/documents/file.txt');
    console.log(fileName);  //  file.txt

  • Get File Extension: path.extname(path) This method returns the extension of a file path.


    const path = require('path');

    const fileExtension = path.extname('/home/user/documents/file.txt');
    console.log(fileExtension); //  .txt

  • These are just a few examples of the functions provided by the `path` module. The module also includes other utility functions for handling paths, making it easier to work with file and directory locations in a cross-platform manner.

No comments:

Post a Comment