To get the extension of a file from a path, you can use the
extname() method from the global
path module in Node.js.
For example, let's say you have a path like
myFolder/myFile.txt from which you need to get the extension of the file. For that, you can pass the path string as an argument to the method like this,
// require path const path = require("path"); // path string const pathStr = "myFolder/myFile.txt"; // get the extension of the file from the path // using the path.extname() method const extension = path.extname(pathStr); // ".txt"
extname()method returns the extension of the file from the path.
- If no extension is identified from the path the method returns an empty string
See the above code live in repl.it
That's all! 😃