How to use the extension function from mime-types

Find comprehensive JavaScript mime-types.extension code examples handpicked from public code repositorys.

mime-types.extension returns the file extension associated with a given MIME type.

5
6
7
8
9
10
11
12
13
14
try {
    let output = '';

    if (input && input.length > 0) {                

        const result = mime.extension(input);   

        if (result) {
            output = result;
        }
fork icon184
star icon987
watch icon19

52
53
54
55
56
57
58
59
60
61
}

function getFileNameFromContentType(contentType, url) {


  let extension = mime.extension(contentType)

  url = removeQueryString(url);
  const fileNameWithoutExtension = removeExtension(path.basename(url));
  return `${sanitize(fileNameWithoutExtension)}.${extension}`;
fork icon16
star icon98
watch icon3

How does mime-types.extension work?

mime-types.extension(type) is a function in the mime-types library that returns the file extension associated with a given MIME type. When you provide a valid MIME type as an argument to the extension function, it returns the corresponding file extension. If the MIME type is not recognized, the function returns false. Internally, mime-types uses a database of MIME types and their corresponding file extensions to perform the lookup.

42
43
44
45
46
47
48
49
50
51
    // Check if user has custom mapping for this content type first
    if (essence in mimeAndFileExtensionMapping) {
        const ext = mimeAndFileExtensionMapping[essence];
        return ext.replace(/^(\.)+/, '');
    }
    return mime.extension(contentTypeString) || '';
}

public static isBrowserSupportedImageFormat(contentTypeString: string | undefined): boolean {
    // https://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
fork icon2
star icon64
watch icon2

544
545
546
547
548
549
550
551
552
553
let filename = files.find((name) => name.startsWith(filenamePrefix));

if (!filename) {
  return new Promise((resolve) => {
    https.get(url, (res) => {
      const ext = mimeTypes.extension(
        res.headers["content-type"] || "image/png"
      );
      const dest = `${filenamePrefix}.${ext}`;
      const destStream = fs.createWriteStream(settings.output(dest));
fork icon3
star icon43
watch icon1

+ 3 other calls in file

Ai Example

1
2
3
4
const mime = require("mime-types");

// Get the file extension for a given MIME type
const extension = mime.extension("application/pdf"); // Returns 'pdf'

599
600
601
602
603
604
605
606
607
608

if (!Buffer.isBuffer(response.body)) {
  throw new Error(`Unexpected response: '${versionUrl}'`);
}

let mimeExtension = mime.extension(response.headers['content-type']);
const result = {
  headers: response.headers,
  body: response.body,
  extension: mimeExtension ? `.${mimeExtension}` : '',
fork icon3
star icon5
watch icon0

40
41
42
43
44
45
46
47
48
49

const [ header, data ] = content.split(';base64,')
const [ word, contentType ] = header.split(':')
if (!contentType) { return null }

const ext = mime.extension(contentType) || 'unk'
const buffer = new Buffer(data, 'base64')

const id = crypto.randomBytes(20).toString('hex')
const filename = path.join(basename, `${id}.${ext}`)
fork icon2
star icon8
watch icon3

249
250
251
252
253
254
255
256
257
258
  responseType: 'arraybuffer'
})
.then(response => {
  var buffer = Buffer.from(response.data, 'binary');
  const contentType = response.headers['content-type'];
  const ext = extension(contentType);
  var new_filename = crypto.randomBytes(16).toString('hex');
  const filepath = __dirname + "/media-files/" + new_filename + ext;
  const filepath2 = "media-files/" + new_filename + ext;
  fs.writeFile(filepath, buffer, () => {
fork icon0
star icon0
watch icon1

359
360
361
362
363
364
365
366
367
368
   responseType: 'stream',
   headers: {
      'Referer': referer || ''
   }
}).then(async (response) => {
   let extension = filename ? filename.split`.` [filename.split`.`.length - 1] : mime.extension(response.headers['content-type'])
   let file = fs.createWriteStream(`${tmpdir()}/${filename || Func.uuid() + '.' + extension}`)
   response.data.pipe(file)
   file.on('finish', async () => {
      let data = {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
/* ==== ATENÇÃO ======= PARA DOCS precisa aplicar descriptografar arquivo */
        var buffer = await inst.downloadFile(message);

        /* salvar o arquivo recebido na mensagem em diretorio local (para cliente acessar via link do front) */
        var now = new Date();
        var nameFile = message.id  + '-' + now.getSeconds() + "." +  mime.extension(message.mimetype);
        var fileName = "";
        var base_dir = "";
        var ret = ""; 
        var tipo = ""; 
fork icon0
star icon0
watch icon1

+ 2 other calls in file

53
54
55
56
57
58
59
60
61
   }

//    console.log(chats);
    
   //  console.log(message)
   var ext = mime.extension(message.mimetype);

     if(message){
       var nameFile = "naoDefinido";
fork icon0
star icon0
watch icon1

+ 2 other calls in file

118
119
120
121
122
123
124
125
126
127
// [ext] - .js
if (typeof data.filename === "string") {
	// check that filename is data uri
	let match = data.filename.match(/^data:([^;,]+)/);
	if (match) {
		const ext = mime.extension(match[1]);
		const emptyReplacer = replacer("", true);

		replacements.set("file", emptyReplacer);
		replacements.set("query", emptyReplacer);
fork icon0
star icon0
watch icon1

+ 3 other calls in file

116
117
118
119
120
121
122
123
124
125
//*******************************************//
const getRandom = (ext) => {
	return `${Math.floor(Math.random() * 10000)}${ext}`
}
const getExtension = async (type) => {
return await mimetype.extension(type)
 }
const getBuffer = (url, options) => new Promise(async (resolve, reject) => { 
options ? options : {}
await axios({method: "get", url, headers: {"DNT": 1, "Upgrade-Insecure-Request": 1}, ...options, responseType: "arraybuffer"}).then((res) => {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

11
12
13
14
15
16
17
18
19
20
21
22
  destination: function (req, file, cb) {
    cb(null, "multimedia/itemsGallery/");
  },


  filename: function (req, file, cb) {
    cb(null, file.originalname + "." + mime.extension(file.mimetype));
  },
});


var upload = multer({ storage: storage });
fork icon0
star icon0
watch icon1

9
10
11
12
13
14
15
16
17
18
 * @param {string} response
 * @returns
 */
const fileTypeFromFile = async (response) => {
    const type = response.headers['content-type'] ?? null
    const ext = mimeDep.extension(type)
    return {
        type,
        ext,
    }
fork icon0
star icon0
watch icon0

85
86
87
88
89
90
91
92
93
94
    if (mime?.toLowerCase()?.trim() === "image/jpg") {
        newExtension = 'jpg';
    } else if (mime?.toLowerCase()?.trim() === "text/mermaid") {
        newExtension = 'txt';
    } else {
        newExtension = mimeTypes.extension(mime) || "dat";
    }
}

// if the note is already named with extension (e.g. "jquery"), then it's silly to append exact same extension again
fork icon0
star icon0
watch icon244