Languages
[Edit]
EN

Node.js - get file name without extension from path

0 points
Created by:
Reilly-Collier
410

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

Output:

index.js

Note:

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

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.

❤️💻 🙂

Join