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

Last updated on September 29, 2022
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

11 Amazing New Features in ES13

11 Amazing New Features in ES13
Get up to speed with all the latest features added in ECMAScript 13 to modernize your JavaScript with shorter and more expressive code.

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.

  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

// ❌ TypeError: Received type of boolean instead of string

// ❌ TypeError: Received type of URL instead of string
path.parse(new URL('')).name;

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

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

See also