Node.js get file extension

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

    Try this one

    const path = require('path');
    
    function getExt(str) {
      const basename = path.basename(str);
      const firstDot = basename.indexOf('.');
      const lastDot = basename.lastIndexOf('.');
      const extname = path.extname(basename).replace(/(\.[a-z0-9]+).*/i, '$1');
    
      if (firstDot === lastDot) {
        return extname;
      }
    
      return basename.slice(firstDot, lastDot) + extname;
    }
    
    // all are `.gz`
    console.log(getExt('/home/charlike/bar/file.gz'));
    console.log(getExt('/home/charlike/bar/file.gz~'));
    console.log(getExt('/home/charlike/bar/file.gz+cdf2'));
    console.log(getExt('/home/charlike/bar/file.gz?quz=zaz'));
    
    // all are `.tar.gz`
    console.log(getExt('/home/charlike/bar/file.tar.gz'));
    console.log(getExt('/home/charlike/bar/file.tar.gz~'));
    console.log(getExt('/home/charlike/bar/file.tar.gz+cdf2'));
    console.log(getExt('/home/charlike/bar/file.tar.gz?quz=zaz'));
    
    

提交回复
热议问题