Node.js — Get a File Name (With or Without Extension)

Node.js can extract a file name from a given path. The path can be an absolute or relative path. You can then let Node.js do the parsing and return the file path.

Node.js Series Overview

Get the File Name With Extension

You can retrieve the file name from a given path using Node.js’ path module. The path module comes with the Node.js runtime.

Retrieve the file name using the Path.basename method. This method returns the trailing name component from a file path, including the file extension. For example, it returns avatar.png from the path /home/user/avatar.png:

import Path from 'path'

const filename = Path.basename('/home/user/avatar.png')  
// 'avatar.png'

Get the File Name Without Extension

Sometimes you want to retrieve the file name without the extension. You may use the built-in Node.js path module to do that. You can use the Path.parse method to parse a given file path into the individual parts. Then, retrieve the file name without the extension:

import Path from 'path'

const filename = Path.parse('/home/user/avatar.png').name  
// 'avatar'

Use the @supercharge/fs Package

I’m the maintainer of the @supercharge/fs package providing convenient file system utilities. The @supercharge/fs package comes with handy methods to retrieve the file name:

  • Fs.basename(path): returns the file name with extension
  • Fs.basename(path): returns the file name without extension

Here’s the sample code on how to use both functions:

import Fs from '@supercharge/fs'

Fs.basename('/home/user/avatar.png')  
// 'avatar.png'

Fs.filename('/home/user/avatar.png')  
// 'avatar'

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.