Explain Codes LogoExplain Codes Logo

Node.js get file extension

javascript
file-extension
string-manipulation
utility-functions
Nikita BarsukovbyNikita Barsukov·Sep 13, 2024
TLDR

In Node.js, you can quickly get a file's extension with the path.extname() function from the path module:

const path = require('path'); console.log(path.extname('sample.txt')); // Will show: '.txt'

This function will extract the extension from the specified filename, simple as pie!

Techniques for complex filenames

What if your filename isn't so straightforward? Say, with multiple extensions or even no extension at all, like .gitignore or awesome.tar.gz. Here's a technique using split(), filter(), and join():

const fullName = 'archive.tar.gz'; const parts = fullName.split('.').filter(Boolean); if (parts.length > 1) { const ext = parts.slice(1).join('.'); console.log(ext); // Ta-da: 'tar.gz' } else { console.log('No extension, eh?'); }

This splits the filename by '.', filters out any empty results (in case of leading '.'), and combines them back if there's more than one.

Dealing with URLs and query strings

Now, would you look at that, your filename might actually be a URL with query strings attached! In this case, here's a method with a bit of URL parsing in the mix:

const url = require('url'); const path = require('path'); const myUrl = 'http://example.com/file.txt?query=123'; const pathname = url.parse(myUrl).pathname; // strip off that pesky query string const extension = path.extname(pathname); console.log(extension); // Voila: '.txt'

Here, we parse the URL to get rid of the query parameters and properly extract the extension.

Tuning performance for large filenames

Got a big filename? No worries! Using lastIndexOf() or substr() can give a performance boost when dealing with very long strings:

const filename = 'worlds_biggest_novel.docx'; const lastDot = filename.lastIndexOf('.'); if (lastDot > 0) { const ext = filename.substr(lastDot); console.log(ext); // Gotcha: '.docx' } else { console.log('No extension, are you kidding me?'); }

This one is like a game of Hide and Seek with better performance for larger filenames.

Utilising utility functions for efficiency

For better code reuse and edge case handling, you can wrap this logic inside a utility function:

function getFileExtension(filePath) { const parts = filePath.split('.').filter(Boolean); return parts.length > 1 ? parts.slice(1).join('.') : 'Nada!'; } console.log(getFileExtension('secret.tar.gz')); // Look Ma: 'tar.gz' console.log(getFileExtension('README')); // No extension, this ain't Hogwarts!

This utility function provides a one-stop solution for extension extraction while also managing those pesky edge cases.

Express compatibility considerations

If you're using Express 3, ensure your settings allow file uploads to keep their original extensions:

app.use(express.bodyParser({ keepExtensions: true }));

Everyone likes to keep their extensions, right? It's a hairstyle thing.

Delving deeper into string methods

When handling string manipulations, it's important to understand substr() vs substring(). Just like salt and sugar, they look the same but taste different:

const negativeStart = 'unexpected.situation.txt'; console.log(negativeStart.substr(-4)); // Here ya go: '.txt' const positiveStart = 'expected.outcome.pdf'; console.log(positiveStart.substring(17)); // Nice one, output: '.pdf'

Remember, substr() can handle negative 'start' positions, but substring() can't. So use wisely, dear coder!