How to use the lookup function from mime-types

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

mime-types.lookup is a function in the mime-types library that returns the MIME type for a given file extension.

175
176
177
178
179
180
181
182
183
184
type(mime_type) {
    // Remove leading dot from mime type if present
    if (mime_type.startsWith('.')) mime_type = mime_type.substring(1);

    // Determine proper mime type and send response
    this.header('content-type', mime_types.lookup(mime_type) || 'text/plain');
    return this;
}

/**
fork icon53
star icon724
watch icon16

35
36
37
38
39
40
41
function resolveMimeType(query) {
    if (mimeTypes.extensions[query]) {
        return query; //  already a mime-type
    }

    return mimeTypes.lookup(query) || undefined; //  lookup() returns false; we want undefined
}
fork icon101
star icon443
watch icon42

How does mime-types.lookup work?

mime-types.lookup is a function in the mime-types library that is used to determine the MIME type for a given file extension. When called with a file extension as its argument, mime-types.lookup returns the corresponding MIME type for that extension. If the extension is not recognized by the library, the function returns false. Internally, mime-types.lookup maintains a mapping of file extensions to MIME types in a lookup table. The table is loaded from a file called mime.types when the library is initialized. The mime.types file contains a list of MIME type definitions for common file extensions. If the MIME type for a file extension is not found in the lookup table, mime-types.lookup uses a set of heuristics to try to determine the correct MIME type based on the file's contents. These heuristics include examining the file's contents for known patterns or magic numbers that indicate its file type. mime-types.lookup can also accept an optional fallback argument, which is returned if no MIME type is found for the given file extension. Note that mime-types.lookup is part of the mime-types library, which is a collection of utility functions for working with MIME types in JavaScript. It is useful for tasks such as serving static files over HTTP, validating file uploads, or generating file download links.

53
54
55
56
57
58
59
60
61
62
      'Bad Response (' + response.status + ') loading image: ' + response.url));
  }

  // Using mime.lookup insteand of `// response.headers.get('Content-Type');`, as some
  // publishers use an invalid value for the content-type.
  const contentType = mime.lookup(imageUrl);
  return this.saveImages(response.body, destFile, contentType);
})
.then(savedUrls => {
  return savedUrls;
fork icon58
star icon547
watch icon30

1
2
3
4
5
6
7
8
9
10

module.exports = function getResourceType(contentType, path) {
    if (contentType && contentType.match) {
        contentType = contentType.toLowerCase();
        if (contentType.match(/application/)) {
            const newContentType = mime.lookup(path);
            if (newContentType) {
                contentType = newContentType;
            }
        }
fork icon23
star icon154
watch icon5

Ai Example

1
2
3
4
5
6
7
const mimeTypes = require("mime-types");

const fileExtension = "jpg";

const mimeType = mimeTypes.lookup(fileExtension);

console.log(mimeType); // Output: image/jpeg

In this example, we start by importing the mime-types library. We then define a variable called fileExtension that contains the file extension we want to look up the MIME type for. In this case, we're using 'jpg' as an example. We call mimeTypes.lookup with fileExtension as its argument to get the corresponding MIME type. We store the result in a variable called mimeType. Finally, we log mimeType to the console, which outputs 'image/jpeg' because that is the MIME type for files with a .jpg extension. Note that this is just a simple example, and mime-types.lookup can be used with any file extension to get its corresponding MIME type.

73
74
75
76
77
78
79
80
81
82
Uploader.prototype.s3PathForFile = function (localPath, tag) {
  return path.join(S3_DIR, tag, localPath);
};

Uploader.prototype.contentType = function(path) {
  return mime.lookup(path) || DEFAULT_CONTENT_TYPE ;
};

new Uploader().uploadTheme();
new Uploader().uploadAssets();
fork icon362
star icon0
watch icon2

47
48
49
50
51
52
53
54
55
56
this.logger.verbose('Syncing to AWS!');
const sync = await client.sync('cache', 's3://pixelmap.art', {
  del: false,
  sizeOnly: false,
  commandInput: {
    ContentType: (syncCommandInput) => mime.lookup(syncCommandInput.Key) || 'image/png',
  },
});
console.log(sync);
this.logger.verbose('Sync to AWS complete!');
fork icon16
star icon38
watch icon5

93
94
95
96
97
98
99
100
101
102
graph.add(
  url,
  ns.stat('size'),
  this.serverMeta.size)

const mimeType = mime.lookup(this.target.url)
if (mimeType) { // Is the file has a well-known type,
  const type = 'http://www.w3.org/ns/iana/media-types/' + mimeType + '#Resource'
  graph.add(
    url,
fork icon5
star icon24
watch icon8

7
8
9
10
11
12
13
14
15
16
module.exports = client => {
  client.on('message', async message => {
    if (message.channel.type !== 'text' || message.author.bot) return;
    if (!message.attachments) return;
    for (const attachment of message.attachments.values()) {
      let contentType = mimeType.lookup(attachment.url);
      if (!contentTypes.some(type => contentType === type)) continue;
      if (attachment.name.endsWith('.log')) {
        contentType = 'text/log';
      }
fork icon19
star icon11
watch icon4

23
24
25
26
27
28
29
30
31
32
if (!options) options = {}

var filename = options.filename
var mimeType
if (filename) {
  mimeType = mime.lookup(filename)
}
var parentID = options.parent

var metaOpts = {
fork icon2
star icon17
watch icon2

10
11
12
13
14
15
16
17
18
19

const file = await new Promise((resolve, reject) => {
  let f = null;
  f = new File([fs.readFile(filePath)], path.basename(filePath), {
    lastModified,
    type: mime.lookup(filePath) || '',
  });

  if (f) resolve(f);
});
fork icon7
star icon9
watch icon7

1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
    capture(e);
  }

  return res.status(200).send({
    data: Buffer.from(decryptedBuffer, "base64"),
    mimeType: mimeFromFile ? mimeFromFile : mime.lookup(fileName),
    fileName: fileName,
    ok: true,
  });
} catch (error) {
fork icon4
star icon8
watch icon4

+ 2 other calls in file

65
66
67
68
69
70
71
72
73
74
const { path } = await tracksModel.getById(album.trackIds[0])
return walk(dirname(path))
  .pipe(
    filter(({ path, stats }) => {
      if (stats.isFile()) {
        const type = mime.lookup(extname(path))
        return (
          type === 'image/jpeg' ||
          type === 'image/gif' ||
          type === 'image/png' ||
fork icon3
star icon54
watch icon0

69
70
71
72
73
74
75
 * console.log(extension);
 * > 'img'
 */
exports.getPenultimateFileExtension = (filePath) => {
  const ext = _.last(_.initial(exports.getFileExtensions(filePath)))
  return !_.isNil(ext) && mime.lookup(ext) ? ext : null
}
fork icon0
star icon6
watch icon3

55
56
57
58
59
60
61
62
63
64

let commandInputConfig;

commandInputConfig = {
    ...(!disableACL && { ACL: 'public-read' }), ContentType: (syncCommandInput) => (
        mime.lookup(syncCommandInput.Key) || 'text/html'
    )
};

if (CACHE_CONTROL)
fork icon0
star icon3
watch icon4

1501
1502
1503
1504
1505
1506
1507
1508
1509
1510


if (fs.existsSync(filename) && BINARY_FILENAME !== '') {
  let varFileSize = await getFilesizeInMegabytes(filename);
  let varFileSizeByte = varFileSize * (1024 * 1024);
  let getMimeType = mime.lookup(filename);
  ////console.log("varFileSize:", varFileSize);
  //logger.info(new Date() + ": getMimeType: " + getMimeType);
  //logger.info(new Date() + ': FileSize: ' + varFileSize);
  let APIResult = null;
fork icon1
star icon1
watch icon1

+ 4 other calls in file

260
261
262
263
264
265
266
267
268
269
  contentType = value.headers['content-type'];
}

// or guess it from the filepath or filename
if (!contentType && (options.filepath || options.filename)) {
  contentType = mime.lookup(options.filepath || options.filename);
}

// fallback to the default content type if `value` is not simple value
if (!contentType && typeof value == 'object') {
fork icon0
star icon1
watch icon1

+ 14 other calls in file

393
394
395
396
397
398
399
400
401
402

  res.writeHead(206, {
    'Accept-Ranges': 'bytes',
    'Content-Length': chunksize.toString(),
    'Content-Range': `bytes ${dataStart}-${dataEnd}/${data.length}`,
    'Content-Type': mime.lookup(path.basename(assetPath)),
  });

  return data.slice(dataStart, dataEnd + 1);
}
fork icon615
star icon0
watch icon99

+ 4 other calls in file

481
482
483
484
485
486
487
488
489
490
// The list of actions/operations/transactions is either in a "actions" file
// or directly in the body
let inputStream, parseStreams
const transactionSchema = [...req.dataset.schema, { key: '_id', type: 'string' }, { key: '_action', type: 'string' }]
if (req.files && req.files.actions && req.files.actions.length) {
  let actionsMime = mime.lookup(req.files.actions[0].originalname)

  if (req.files.actions[0].mimetype === 'application/zip') {
    // handle .zip archive
    const directory = await unzipper.Open.file(req.files.actions[0].path)
fork icon6
star icon26
watch icon4

+ 2 other calls in file

5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
// GET FILE STATS
let stats = fs.statSync(filename)

if (stats) {

    let type = mime.lookup(filename)

    if (!type) {
        type = 'inode/directory'
    }
fork icon2
star icon5
watch icon1

+ 7 other calls in file

79
80
81
82
83
84
85
86
87
88
console.log("> [outline-robot] Sending the Request with Image");

let contentType;

const imageName = imageConfluenceURL.split("/").pop().split("?")[0];
contentType = mime.lookup("./imgs/" + imageName);

let res = await axios({
  method: "POST",
  url: process.env.OUTLINE_API_URL + "/api/attachments.create",
fork icon2
star icon2
watch icon1