How to Get a File Name Without the Extension in Node.js

To get the name of a file without the extension in Node.js, use the parse() method from the path module to get an object representing the path. The name property of this object will contain the file name without the extension.

For example:

const path = require('path');

path.parse('index.html').name; // index

path.parse('package.json').name; // package

path.parse('image.png').name; // image

The parse() method

The parse() method returns an object with properties that represent the major parts of the given path. The object it returns has the following properties:

  1. dir – the directory of the path.
  2. root – the topmost directory in the operating system.
  3. base – the last portion of the path.
  4. ext – the extension of the file.
  5. name – the name of the file without the extension.
path.parse('C://Code/my-website/index.html');

/*
Returns:
{
  root: 'C:/',
  dir: 'C://Code/my-website',
  base: 'index.html',
  ext: '.html',
  name: 'index'
}
*/

If the path is not a string, parse() throws a TypeError.

// ❌ TypeError: Received type of number instead of string
path.parse(123).name;

// ❌ TypeError: Received type of boolean instead of string
path.parse(false).name;

// ❌ TypeError: Received type of URL instead of string
path.parse(new URL('https://example.com/file.txt')).name;

// ✅ Received correct type of string
path.parse('index.html').name; // index


Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *