Node.js get file extension

后端 未结 13 974
后悔当初
后悔当初 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:38

    path.extname will do the trick in most cases. However, it will include everything after the last ., including the query string and hash fragment of an http request:

    var path = require('path')
    var extname = path.extname('index.html?username=asdf')
    // extname contains '.html?username=asdf'
    

    In such instances, you'll want to try something like this:

    var regex = /[#\\?]/g; // regex of illegal extension characters
    var extname = path.extname('index.html?username=asdf');
    var endOfExt = extname.search(regex);
    if (endOfExt > -1) {
        extname = extname.substring(0, endOfExt);
    }
    // extname contains '.html'
    

    Note that extensions with multiple periods (such as .tar.gz), will not work at all with path.extname.

提交回复
热议问题