Cheikhany Ejiwen

Software Engineer in San Francisco

7 years' experience

Introduction to the Path Module in Node.js

The "Path" module is undoubtedly one of the most valuable built-in modules in NodeJS. By effectively utilizing this module, we can significantly enhance the clarity and organization of our code while also reducing the time spent on maintenance. This article aims to explore four helpful functions that streamline path manipulation in our projects, making them more accessible and efficient. Let's delve into these functions and discover how they can simplify our development workflow.


path.dirname

The "path.dirname()" method returns the directory name of a given path. Knowing the directory in which a file is located proves to be highly beneficial.

let ourPath = path.dirname('c:/data/code/test.js');
console.log(ourPath); // result -> c:/data/code


path.join

The join method takes two or more path segments and merges them into a single string that forms a valid file path. For example, let's consider a scenario where we require the file path of a JPG image named "myDog.jpg" for simplicity's sake. This method allows us to efficiently construct the complete file path by combining individual path segments.

let filepath = path.join(__dirname, '/images/pics/',myDog,'jpg);
console.log(filePath); // result -> C:/...../iamges/pics/myDog.jpg


path.extname

extname method allows us to know the extension of the given path.

let myHtml = path.extname('index.html);
console.log(myhtml); // result -> .html

Check the official documentation (HERE) for more information.