Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js get file extension

People also ask

How do I know the extension of a node js file?

extname() method is used to get the extension portion of a file path. The extension string returned from the last occurrence of a period (.) in the path to the end of the path string. If there are no periods in the file path, then an empty string is returned.

How do I find the filename in node JS?

Fs. basename(path) : returns the file name with extension. Fs. basename(path) : returns the file name without extension.

What is .node file extension?

A NODE file contains an addon, which is a compiled library of functions used by one or more Node. js applications. It stores binary data compiled from a GYP file written in the C++ programming language. NODE files are similar to .

How can I get file extensions with JavaScript?

Using split() and pop() method: The first part will be the filename and the second part will be the extension of the file. The extension can then be got by popping from the array the last string with the pop() method. This is hence the file extension of the file selected.


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 here
function 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}));

It's a lot more efficient to use the substr() method instead of split() & pop()

Have a look at the performance differences here: http://jsperf.com/remove-first-character-from-string

// returns: 'html'
var path = require('path');
path.extname('index.html').substr(1);

enter image description here

Update August 2019 As pointed out by @xentek in the comments; substr() is now considered a legacy function (MDN documentation). You can use substring() instead. The difference between substr() and substring() is that the second argument of substr() is the maximum length to return while the second argument of substring() is the index to stop at (without including that character). Also, substr() accepts negative start positions to be used as an offset from the end of the string while substring() does not.