DEV Community

Cover image for How to get the extension of a file from the path in Node.js?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to get the extension of a file from the path in Node.js?

Originally posted here!

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"
Enter fullscreen mode Exit fullscreen mode
  • The 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! 😃

Feel free to share if you found this useful 😃.


Top comments (0)