Tutorial

Introduction to the Path Module in Node.js

Published on July 10, 2019
Default avatar

By Cooper Makhijani

Introduction to the Path Module in Node.js

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Cooper Makhijani

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel