Node.js — Get a File‘s Extension

In some situations, you may need to retrieve the extension of a file on your local disk. Node.js comes with built-in functionality that you can use in your application.

This tutorial shows you how to retrieve the file extension in Node.js.

Node.js Series Overview

Retrieve the File Extension

Node.js’ integrated path module provides a Path.extname method. This method accepts a file path as a string. You can either use the Path.extname(path) method directly in your code or create yourself a utility function.

Here’s a sample utility method returning a file’s extension:

import Path from 'path'

/**
 * Returns the current operating system release version.
 *
 * @param {String} filePath
 *
 * @returns {String}
 */
function fileExtension (filePath) {  
  return Path.extname(filePath)
}

You may then use the fileExtension utility method like this:

fileExtension('tutorial.md')  
// '.md'

fileExtension('fs.tutorial.md')  
// '.md'

fileExtension('tutorial.')  
// '.'

fileExtension('tutorial')  
// ''

fileExtension('.md')  
// ''

fileExtension('.tutorial.md')  
// '.md'

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 a handy Fs.extension(path) method returning the file extension of the given path (including the dot):

import Fs from '@supercharge/fs'

Fs.extension('tutorial.md')  
// '.md'

Fs.extension('fs.tutorial.md')  
// '.md'

Fs.extension('tutorial.')  
// '.'

Fs.extension('tutorial')  
// ''

Fs.extension('.md')  
// ''

Fs.extension('.tutorial.md')  
// '.md'

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.