How to Get a File Name Without the Extension in Node.js
Last updated on September 29, 2022

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

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:
dir
- the directory of the path.root
- the topmost directory in the operating system.base
- the last portion of the path.ext
- the extension of the file.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

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
- How to Get a File Extension in Node.js
- How to Convert JSON to XML in Node.js
- How to Get the Short Name of a Month in JavaScript
- How to Fix the "structuredClone is not defined" Error in Node.js
- How to Get the Mouse Position in React
- How to Capitalize the First Letter of Each Word in an Array in JavaScript