Node.js get file extension Node.js get file extension javascript javascript

Node.js get file extension


I believe you can do the following to get the extension of a file name.

var path = require('path')path.extname('index.html')// returns'.html'


Update

Since the original answer, extname() has been added to the path module, see Snowfish answer

Original answer:

I'm using this function to get a file extension, because I didn't find a way to do it in an easier way (but I think there is) :

function getExtension(filename) {    var ext = path.extname(filename||'').split('.');    return ext[ext.length - 1];}

you must require 'path' to use it.

another method which does not use the path module :

function getExtension(filename) {    var i = filename.lastIndexOf('.');    return (i < 0) ? '' : filename.substr(i);}


// you can send full url herefunction getExtension(filename) {    return filename.split('.').pop();}

If you are using express please add the following line when configuring middleware (bodyParser)

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