DEV Community

Discussion on: Detect extension in a directory using node js

Collapse
 
davelsan profile image
David Velasco

In Node.js, personally I prefer to use the built-in path methods.

path.parse

const filepath = 'path/to/file.js';
path.parse(filepath).ext;  // => .js

path.extname

const filename = 'file.js';
path.extname(filename);. // => .js

In any case, make sure you check the returns of split and pop.

  • String.prototype.split() can return an empty string if the separator is the last character of the string; or the entire string if the separator is not found.
  • Array.prototype.pop() can return undefined when used on an empty array.
Collapse
 
hilleer profile image
Daniel Hillmann

Was about to comment this, but you were faster than me. Totally agreed here :)

Collapse
 
jalal246 profile image
Jalal 🚀

Thanks, David!

Agreed. Using built-in methods are always better than reinventing the wheel. But, we still need to read project entry assuming it's index without knowing the extension. Is It .ts or .js?

These built-ins, helpful when knowing the full name with the extension included file.js. However, I tried to introduce a method to extract an anonymous extension.