Node.js: Get File Name and Extension from Path/URL

Last updated on April 2, 2021 A Goodman Loading... Post a comment

The path module (one of the core modules of Node.js) gives us some methods to simply retrieve the name and extension of a file from a path or web URL:

  • path.basename(path: string, extension?: string): Returns the file name with the extension if extension is not passed. On the other hand, If extension is given, the method returns the file name without the extension.
  • path.extname(path): Return the file extension.
  • path.wind32.basename(path: string, extension?: string): Used to deal with Windows-style paths which contain double-backslashes


The code:

const path = require('path');

// File path
SAMPLE_PATH = '/Users/goodman/Desktop/dev/node_kindacode/package.json';

const name1 = path.basename(SAMPLE_PATH);
const ext1 = path.extname(SAMPLE_PATH);
const nameWithoutExt1 = path.basename(name1, ext1);
  'Name without extenions:',

// Web URL

const name2 = path.basename(SAMPLE_URL);
const ext2 = path.extname(SAMPLE_URL);
const nameWithoutExt2 = path.basename(name2, ext2);
  'Name without extenions:',


Filename: package.json Extension: .json Name without extenions: package
Filename: nodejs-file.jpg Extension: .jpg Name without extenions: nodejs-file

path.win32.basename() use cases

Note: If your Node.js program only runs on Windows then you don’t need to care about path.win32.basename(). This is for macOS/Linux users or people who want to achieve consistent results when working with Windows file paths on any operating system.

Using the path.basename() method might return an unwanted result if your Node.js program is running on macOS (or Ubuntu) and the input path is Windows-style with double-backslashes like this:


In this case, we need to use path.win32.basename() instead to ensure you get the correct result everywhere:


const path = require('path');

const FILE_PATH = "C:\\Personal\\MyFolder\\MyFile.jpg";

// Do NOT use this
console.log('Unwanted result:', path.basename(FILE_PATH));

// Use this
console.log('Correct result:', path.win32.basename(FILE_PATH));

The output on my machine (macOS):

Unwanted result: C:\Personal\MyFolder\MyFile.jpg
Correct result: MyFile.jpg

Final Words

You’ve learned how to retrieve the name and extension of a file from a given path or URL. Continue learning more interesting stuff about Node.js by taking a look at the following articles: Top 4 best Node.js Open Source Headless CMS, 6 best Node.js frameworks to build backend APIs, Using Axios to download images and videos in Node.js, How to get all Links from a Webpage using Node.js and Cheerio.

You can also check out our Node.js category page for the latest tutorials and examples.

Related Articles

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x