NodeJS Path Module

Mustafa Ozdemir
baakademi
Published in
2 min readOct 25, 2020

In this blog, we are going to be talking about benefits of path module and its main methods in NodeJS.

Linux and macOS have the same path system. On the other hand, Windows machines have a different path structure.

Linux and macOS: /users/foo/file.txt
Windows: C:\users\foo\file.txt

As shown, it would be kind of tricky to manage the paths of an application which runs between servers that have different operating systems. To overcome these slash-backslash mess, NodeJS provides us a module called path. This module allows us to standardise path operations for us.

The path module is a core module of NodeJS framework, therefore we don’t need to install it as an external module. All we need to do is require and include it in our file.

const path = require('path');

Let’s get information out of a path with those methods.

basename: get the filename part
dirname: get the parent folder of a file
extname: get the file extension

/*Example*/
const image = 'C:/user/foo/image.png';
console.log(path.basename(image)); // image.png
console.log(path.dirname(image)); // C:/user/foo
console.log(path.extname(image)); // .png

Concatenate paths

Let’s assume we have a path called mainpath. We would like to create a folder called testfolder and in the folder we will have a file called image.png. We can use the path.join() method to concatenate these three parts of a path to create a platform independent path.

const mainpath = ‘C:Desktop/user/foo/sample.txt’;
const image = ‘image.png’;
console.log(path.join(path.dirname(fullpath),’testfolder’, image));

The output is as shown below for windows machines.
C:Desktop\user\foo\testfolder\image.png

Normalize paths

The path.normalize() method resolves the specified path, taking care of ‘..’,’\\\\’ etc.

var brokenpath = path.normalize(‘Users/Refsnes/../text’);
console.log(brokenpath);

Windows computers will resolve to
Users\text

Path parse

path.parse() method parses a path to an object with the segments that compose it
root: the root
dir: the folder path starting from the root
base: the file name + extension
ext: the file extension
name: the file name

/*Example*/
const fullpath = ‘C:Desktop/user/foo/text.txt’;
console.log(path.parse(fullpath));

The output of the code is shown down below for windows OSs.

{
root: ‘C:’,
dir: ‘C:Desktop/user/foo’,
base: ‘text.txt’,
ext: ‘.txt’,
name: ‘text’
}

That’s all for this post. Hope you enjoyed it. If you want to learn more about the NodeJS path module, You can check out these links.

--

--