Node.js get file extension

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

    The following function splits the string and returns the name and extension no matter how many dots there are in the extension. It returns an empty string for the extension if there is none. Names that start with dots and/or white space work also.

    function basext(name) {
      name = name.trim()
      const match = name.match(/^(\.+)/)
      let prefix = ''
      if (match) {
        prefix = match[0]
        name = name.replace(prefix, '')
      }
      const index = name.indexOf('.')
      const ext = name.substring(index + 1)
      const base = name.substring(0, index) || ext
      return [prefix + base, base === ext ? '' : ext]
    }
    
    const [base, ext] = basext('hello.txt')
    

提交回复
热议问题