How to get the File Extension of a File using Node
Table of Contents
Because Node is a back-end language, it runs on the server and can perform file system operations.
A common operation is needing to know what the extension of a file is.
In this post, we'll learn how to get the file extension of a file on the file system using Node.
How to get the file extension of a file
Getting the file extension of a file is easy thanks to the built-in path
module.
This module has the extname
method that can be used to get the file extension of a file.
Simply pass it the path of a valid file and it will return the file extension.
JAVASCRIPTimport * as path from "path";
const ext = path.extname("/path/to/file.txt");
console.log(ext);
BASH.txt
In case you have a file name with numerous dots, the extname
method will return the file extension of the last dot.
JAVASCRIPTimport * as path from "path";
const ext = path.extname("/path/to/file.txt.zip");
console.log(ext);
BASH.zip
Keep in mind that if the file has no extension, it will return a blank string:
JAVASCRIPTimport * as path from "path";
const ext = path.extname("/path/to/file");
console.log(ext);
BASH
Conclusion
In this post, we learned how to get the file extension of a file using Node.
Simply import the path
module and use the extname
method with a valid file path.
Thanks for reading and happy coding!
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Getting Started with Express
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor