I send a file through a form, in using forms with multipart/form-data, server side I have file objects in req.files.

This gives me some information such as path, name, size, type, and so on.

{ logo: File { size: 121920, path: '/var/folders/tn/h8lfq1sj7c33c0p30qgkd3mw0000gn/T/upload_b9e85b7cf989482a1760d82b77fd555a', name: 'Screen Shot 2021-06-07 at 21.40.29.png', type: 'image/ PNG ', Hash: null, lastModifiedDate: The 2021-06-07 T22:20:50. 150 z, / /... }}Copy the code

Note that the temporary file path does not have an extension.

If you use this name on the server side, no problem. But I want to change it and use my own naming conventions, so I just need the file extension.

To get it, you can do two things: parse the file name with

const path = require('path')
path.extname(req.files.logo.name) //.png
Copy the code

This does not require any third-party libraries.

Or you can use the miME-types package and look at the MIME types.

const mime = require('mime-types')
mime.extension('text/plain') //txt
mime.extension('image/png') //png
Copy the code