Node.js - get file name without extension from path

0 points
Created by:

In this article, we would like to show you how to get file name without extension from path in Node.js.

1. Import path module using:

const path = require('path');

2. Use path.extname() method with the path you want to get the filename from as an argument to get the file extension. We need to know the file extension, so we can get rid of it in the next step.

3. Use path.basename() method with the path and the optional extension argument so the file extension will be removed leaving only the file name.

Practical example:

const path = require('path');

// example path
const myPath = 'C:/projects/app/index.js';

// get file extension
const extension = path.extname(myPath);

// get file name without extension
const result = path.basename(myPath, extension);

console.log(result); // index




The path.basename() method with one argument (myPath) returns file name with extension from given path.

Alternative titles

  1. Node.js - get filename without extension from path
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂