Node.js get file extension

后端 未结 13 988
后悔当初
后悔当初 2020-12-23 00:16

Im creating a file upload function in node.js with express 3.

I would like to grab the file extension of the image. so i can rename the file and then append the file

13条回答
  •  佛祖请我去吃肉
    2020-12-23 00:51

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

提交回复
热议问题