How to use the contentType function from mime-types

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

The mime-types.contentType function is used to generate a Content-Type header value for a given file extension or MIME type.

39
40
41
42
43
44
45
46
47
48

// Returns a middleware that injects the SocketIO JavaScript
// and a link to the clients side adapters into any HTML file
module.exports = function (configuration) {
  return injector(function (req, res) {
    var header = res.getHeader('content-type') || mime.contentType(path.extname(url.parse(req.url).pathname));
    if (res._header) {
      var matches = res._header.match(/content-type:[\s*](.*)/i);
      header = matches && matches[1];
    }
fork icon27
star icon119
watch icon68

24
25
26
27
28
29
30
31
32
33
function readSource({sources, indexFile}, filename) {
  const fileData = fs.readFileSync(filename, {encoding: null});
  const relativePath = path.relative(sources, filename);
  const isIndexFile = relativePath === indexFile;
  const urlPath = `/${isIndexFile ? '' : relativePath.replace(/\\/g, '/')}`;
  const contentType = mime.contentType(path.extname(filename)) || 'application/octet-stream';
  const cacheControl = isIndexFile ? 'no-cache' : 'public, max-age=31536000';
  const body = zlib.gzipSync(fileData);
  const contentLength = body.length;
  const lastModified = runDate.toUTCString();
fork icon5
star icon10
watch icon3

How does mime-types.contentType work?

mime-types.contentType is a function in the mime-types library that takes a file path or extension and returns the content type associated with that file. In detail, the function first tries to match the file path or extension with a predefined mime type. If a match is found, the function returns the corresponding content type. If no match is found, the function returns false.

97
98
99
100
101
102
103
104
105
106
}

const {contentLength} = stream;

response.setHeader('Content-Length', contentLength);
response.setHeader('Content-Type', contentType(extname(fullPath)));

await pipe([
    stream,
    response,
fork icon258
star icon0
watch icon43

44
45
46
47
48
49
50
51
52
53
  this.deliver(200, JSON.stringify(json));
}

// Files
res.sendAsFile = function (content, ext) {
  res.setHeader('Content-Type', mime.contentType(ext));
  res.end(content);
}

res.sendFile = function (filePath) {
fork icon2
star icon29
watch icon11

Ai Example

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

console.log(mime.contentType("json")); // Output: 'application/json'
console.log(mime.contentType("file.jpg")); // Output: 'image/jpeg'

255
256
257
258
259
260
261
262
263
264
	defaultHeaders['ETag'] = `"${sha}"`;
} else {
	defaultHeaders['Last-Modified'] = stats.mtime.toUTCString();
}

const contentType = mime.contentType(base);

if (contentType) {
	defaultHeaders['Content-Type'] = contentType;
}
fork icon0
star icon2
watch icon1

235
236
237
238
239
240
241
242
243
244

const realPath = size === 0 ? fileDocument.localPath : `${fileDocument.localPath}_${size}`;

try {
  const dataFile = fs.readFileSync(realPath);
  const mimeType = mime.contentType(fileDocument.name);
  response.setHeader('Content-Type', mimeType);
  return response.send(dataFile);
} catch (error) {
  return response.status(404).send({ error: 'Not found' });
fork icon0
star icon1
watch icon0

132
133
134
135
136
137
138
139
140
141
  });
}

if (!getHeaderFromResponse(res, "Content-Type")) {
  // content-type name(like application/javascript; charset=utf-8) or false
  const contentType = mime.contentType(path.extname(filename)); // Only set content-type header if media type is known
  // https://tools.ietf.org/html/rfc7231#section-3.1.1.5

  if (contentType) {
    setHeaderForResponse(res, "Content-Type", contentType);
fork icon0
star icon0
watch icon1

39
40
41
42
43
44
45
46
47
48
 * From Local
 */
return new Promise((res) => {
    const response = {
        headers: {
            'content-type': mimeDep.contentType(extname(url)),
        },
    }
    res({ response, fullPath: url })
})
fork icon0
star icon0
watch icon0