Compose File Paths in Node.js

Node.js·11 min read·Jan 1, 2025

The path module is a core module that provides utilities for working with filepaths in a convenient way.

const path = require('node:path');

Join path segments

To join multiple path segments separated by a forward slash character / into a single normalized filepath string, you can use the path.join() static method:

let filepath = path.join(chunk, ...);

Where:

  • filepath is the full path string composed of all the specified chunks.
  • chunk, ... is a list of comma-separated strings representing filepath chunks.

Example

Let's consider this script that uses the path.join() static method to generate a list of filepath strings.

const path = require('node:path');

let filepaths = [];

const baseDirectory = '~/projects';
const appDirectory = 'calculator';
const files = ['index.js', 'utils/add.js', 'utils/subtract.js'];

for (let file of files) {
  filepaths.push(path.join(baseDirectory, appDirectory, file));
}

console.log(filepaths);

Which will produce this output:

[
  '~/projects/calculator/index.js',
  '~/projects/calculator/utils/add.js',
  '~/projects/calculator/utils/subtract.js'
]

Parse file names

To extract the last component of a filepath string, typically the name of the file or directory, you can use the path.basename() static method:

let filename = path.basename(filepath);

Where:

  • filename is the name of the entry.
  • filepath is the relative or absolute path to the entry.

On the other hand, to only extract its file extension, you can use the extname() static method:

let extension = path.extname(filepath);

Where:

  • extension is the file extension of the entry, if parsable (see below).
  • filepath is the relative or absolute path to the entry.

Note: If the filename doesn't contain a dot character or if there are no dot characters other than the first character, it will return an empty string ''.

For example, both expressions will return an empty string:

path.extname('index')
path.extname('.env')

Example

Let's consider this script that checks if a file has a valid extension:

const path = require('node:path');

function checkFileType(filepath) {
  const allowedExtensions = ['.jpg', '.png', '.gif'];

  const fileName = path.basename(filepath);
  const fileExtension = path.extname(filepath);

  if (!allowedExtensions.includes(fileExtension)) {
    throw new Error(`Error: '${fileName}' doesn't have a valid file extension ('${fileExtension}')`);
  }

  return true;
}

try {
  const filepaths = [
    '~/Documents/pictures/holidays/2024/20240603_01.jpg',
    '~/Downloads/923478432.heic',
  ];

  filepaths.forEach(filepath => {
    console.log(`Checking filepath: '${filepath}' ...`);
    checkFileType(filepath);
    console.log('File OK!');
  });
} catch (error) {
  console.error(error.message);
}

When executed, it will:

  1. Define a function named checkFileType() that takes as argument a filepath and checks if the file extension is equal to '.jpg', '.png', or '.gif'.
  2. Loop on each path string of the filepaths array using a forEach loop.
  3. Invoke the checkFileType() function on each path string.

Which will produce this output:

Checking filepath: '~/Documents/pictures/holidays/2024/20240603_01.jpg' ...
File OK!
Checking filepath: '~/Downloads/923478432.heic' ...
Error: '923478432.heic' doesn't have a valid file extension ('.heic')

Parse directory names

To extract the path to the parent directory of the last element of a path string, you can use the path.dirname() static method:

path.dirname(filepath)

Example

In this example, we're extracting the path of the directory containing the md5.js file:

const path = require('node:path');

console.log(path.dirname('./src/utils/md5.js'));

Which will produce this output:

./src/utils

Parse filepaths

To explode a path string into an object whose properties represent its significant elements, you can use the path.parse() static method:

const { dir, root, base, name, ext } = path.parse(filepath);

Where:

  • dir is the path to the last path element.
  • root is the first path element.
  • base is the last path element.
  • name is the last path element without a file extension.
  • ext is the file extension of the last path element.

Example

In this example, we're extracting all the elements of the specified filepath:

const path = require('node:path');

console.log(path.parse('/Users/razvan/project/nodejs-api/server.js'));

Which will produce this output:

{
  root: '/',
  dir: '/Users/razvan/project/nodejs-api',
  base: 'server.js',
  ext: '.js',
  name: 'server'
}

🗒️ Summary

Here's a summary of what you've learned in this lesson:

  • The node:path core module provides utilities for working with filepaths.
  • The path.join() method joins multiple path segments into a single normalized filepath.
  • The path.basename() method returns the last component of a filepath.
  • The path.extname() method returns the file extension of the last component of a filepath.
  • The path.dirname() method returns the path to the parent directory of the last element of a filepath.
  • The path.parse() method returns an object containing the properties of a filepath.