AI Workshop: learn to build apps with AI →
Working with Files: How to get the file extension in Node.js from the MIME type

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


When handling file uploads with multipart/form-data, the server receives file objects (e.g. in req.files in Express).

Each file object includes path, name, size, type, and similar fields:

{
  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: 2021-06-07T22:20:50.150Z,
//...
  }
}

The temporary file path may not include an extension. To get the extension you can either parse the original file name:

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

This requires no extra packages. Or use the mime-types package and derive the extension from the MIME type:

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

Lessons in this unit:

0: Introduction
1: How to check if a file exists in Node.js
2: How to create an empty file in Node.js
3: How to get the names of all the files in a folder in Node
4: How to get the last updated date of a file using Node.js
5: How to remove a file with Node.js
6: How to write a JSON object to file in Node.js
7: How to empty a folder in Node.js
8: Working with file descriptors in Node
9: Node File Paths
10: Node file stats
11: Working with folders in Node
12: How to use the Node.js fs module with async/await
13: How to get the current folder in Node
14: ▶︎ How to get the file extension in Node.js from the MIME type
15: How to get the file extension in Node.js
16: How to list files in a folder in Node
17: How to mass rename files in Node.js
18: Node.js get all files in a folder recursively
19: Incrementing multiple folders numbers at once using Node.js
20: Save some text to a file in Node.js