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:
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
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.
Sign up and receive a free copy immediately.