Introduction to the Path Module in Node.js

Cooper Makhijani

Many people forget about one of Node’s most useful built-in modules, the path module. It’s a module with methods that help you deal with file and directory path names on the machine’s filesystem. In this article, we’re going to look at five of the tools path provides.

Before we can start using the path module, we have to require it:

const path = require('path');

Something of note: path works a little bit differently depending on your OS, but that's beyond the scope of this article. To read more about the differences in the way path works on POSIX systems and Windows, see the path documentation.

Now that that’s out of the way, let’s look at all the things we can use path for.

path.join

One of the most commonly used path methods is path.join. The join method takes two or more parts of a file path and joins them into one string that can be used anywhere that requires a file path. For this example, let’s say that we need the file path of an image, and we have the name of the image. For simplicity’s sake, we’ll assume it’s a png.

const path = require('path');

let imageName = 'bob_smith';

let filepath = path.join(__dirname, '/images/useravatars/', imageName, '.png');
// We'll talk about what __dirname does a little later on.

console.log('the file path of the image is', filepath);
// the filepath of the image is
// C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png
// (actual output shortened for readability)

path.join documentation

path.basename

According to the path docs, the path.basename method will give you the trailing part of a path. In layman’s terms, it returns either the name of the file or directory that the file path refers to. For this example, let’s say we want to know the name of an image, but we were passed the whole file path.

const path = require('path');

// Shortened for readability
let filepath = 'C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png';

let imageName = path.basename(filepath); 

console.log('name of image:', imageName);
// name of image: bob_smith.png

Now this is cool and all, but what if we want it without the extension? Lucky for us, we just have to tell path.basename to remove it.

const path = require('path');

// Shortened for readability
let filepath = 'C:/Users/.../intro-to-the-path-module/images/useravatars/bob_smith.png';

let imageName = path.basename(filepath, '.png');

console.log('name of image:', imageName);
// name of image: bob_smith

path.basename documentation

path.dirname

Sometimes we need to know the directory that a file is in, but the file path we have leads to a file within that directory. The path.dirname function is here for us. path.dirname returns the lowest level directory in a file path.

const path = require('path');

// Shortened for readability
let filepath = 'C:/Users/.../Pictures/Photos/India2019/DSC_0002.jpg';

let directoryOfFile = path.dirname(filepath);

console.log('The parent directory of the file is', directoryOfFile);
// The parent directory of the file is C:/Users/moose/Pictures/Photos/India2019

path.dirname documentation

path.extname

Say we need to know what the extension of a file is. For our example we’re going to make a function that tells us if a file is an image. For simplicity’s sake, we’ll only be checking against the most common image types. We use path.extname to get the extension of a file.

const path = require('path');

let imageTypes = ['.png', '.jpg', '.jpeg'];

function isImage(filepath) {
  let filetype = path.extname(filepath);

  if(imageTypes.includes(filetype)) {
    return true;
  } else {
    return false;
  }
}

isImage('picture.png'); // true
isImage('myProgram.exe'); // false
isImage('pictures/selfie.jpeg'); // true

path.extname documentation

path.normalize

Many file systems allow the use of shortcuts and references to make navigation easier, such as .. and ., meaning up one directory and current direction respectively. These are great for quick navigation and testing, but it’s a good idea to have our paths a little more readable. With path.normalize, we can convert a path containing these shortcuts to the actual path it represents. path.normalize can handle even the most convoluted paths, as our example shows.

const path = require('path');

path.normalize('/hello/world/lets/go/deeper/./wait/this/is/too/deep/lets/go/back/some/../../../../../../../../..');
// returns: /hello/world/lets/go/deeper

path.normalize documentation

🎉 We're done! That's all we're going to cover in this article. Keep in mind that there's way more to path than what's covered here, so I encourage you to check out the official path documentation. Hopefully you learned something, and thanks for reading!

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#