How to use the getType function from mime

Find comprehensive JavaScript mime.getType code examples handpicked from public code repositorys.

mime.getType is a function that returns the MIME type of a file based on its extension.

15
16
17
18
19
20
21
22
23
24
        return {
                size: stat.size,
                modified: stat.mtime,
                name: filename,
                isDir: isDir,
                mime: isDir ? 'application/directory' : Mime.getType(filename)
        };
}

/**
fork icon31
star icon138
watch icon12

199
200
201
202
203
204
205
206
207
208
 * @returns {RequestBuilder} for chaining
 */

RequestBuilder.prototype.type = function(type) {
  return this.header('Content-Type', ~type.indexOf('/') ?
    type : mime.getType(type));
};

RequestBuilder.prototype.cookie = function(cookie) {
  let cookies = this.template.template.headers['Cookie'];
fork icon80
star icon75
watch icon60

How does mime.getType work?

Sure! mime.getType is a function that returns the MIME type of a file based on its extension. When you call mime.getType with a filename or file extension, it looks up the corresponding MIME type in its internal mapping. If a match is found, it returns the MIME type as a string. If no match is found, it returns null. The mapping used by mime.getType is based on the Apache web server's mime.types file, which associates file extensions with MIME types. The mapping is stored in an internal object when the mime library is loaded. If you want to add additional mappings or override existing ones, you can use the mime.define() method to define custom MIME types. This method takes an object that maps file extensions to MIME types, and adds or overrides the internal mapping. mime.getType is often used in web applications to set the Content-Type header of HTTP responses, which specifies the MIME type of the response body. This is important for ensuring that the client's browser or device can properly interpret and display the content.

116
117
118
119
120
121
122
123
124
125
myMime.getExtension('text/def');  // ⇨ 'leppard'
```

If more than one map argument is provided, each map is `define()`ed (see below), in order.

### mime.getType(pathOrExtension)

Get mime type for the given path or extension.  E.g.

```javascript
fork icon320
star icon0
watch icon21

9
10
11
12
13
14
15
16
17
18

exports.setCustomGetType = (fn) => { customGetType = fn; };

exports.getType = (file, defaultValue) => (
  customGetType(file, defaultValue) ||
  mime.getType(file) ||
  defaultValue
);

let customLookupCharset = mimeType => null; // eslint-disable-line no-unused-vars
fork icon200
star icon974
watch icon32

Ai Example

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

const fileName = "example.png";
const mimeType = mime.getType(fileName);

console.log(mimeType);
// Output: "image/png"

In this example, we first import the mime library. We then define a filename example.png. We call mime.getType(fileName) to get the MIME type of the file based on its extension. In this case, the file extension is .png, so mime.getType returns the MIME type "image/png". We then log the MIME type to the console using console.log(), which outputs "image/png".

235
236
237
238
239
240
241
242
243
244
  req["_parsedUrl"].pathname = "/index.html";
}
if (fs.existsSync(path.join(__dirname, "./www/" + req["_parsedUrl"].pathname)) && path.extname(req["_parsedUrl"].pathname) != "") {
  file = fs.readFileSync(path.join(__dirname, "./www/" + req["_parsedUrl"].pathname));
  cfg = config.readConfig();
  res.set('content-type', mime.getType(path.join(__dirname, "./www/" + req["_parsedUrl"].pathname)));
  if (path.extname(req["_parsedUrl"].pathname) != ".js" && path.extname(req["_parsedUrl"].pathname) != ".png" && path.extname(req["_parsedUrl"].pathname) != ".css") {
    additional.showRequestInLogs(req, res);
  }
  ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
fork icon11
star icon20
watch icon3

29
30
31
32
33
34
35
36
37
38
39
  baseURL: '',
};


function addFile(builder, url, file) {
  const headers = {
    'Content-Type': mime.getType(file) || 'application/octet-stream',
  };
  builder.addExchange(url, 200, headers, fs.readFileSync(file));
}

fork icon6
star icon52
watch icon7

12
13
14
15
16
17
18
19
20
21
22
    this.writeHead(200, {'Content-Type': 'application/json'});
    this.end(JSON.stringify({ error_code, error_msg }));
}


function sendStream(filepath){
    this.writeHead(200, {'Contet-Type': mime.getType(path.basename(filepath))});
    var stream = fs.readFileSync(filepath);
    this.end(stream);
}

fork icon2
star icon5
watch icon0

64
65
66
67
68
69
70
71
72
73
			console.log(e);
			res.status(404).send('<h1>page not found</h1>');
		}
	}
} else {
	let mime_type = mime.getType(file_path);
	if	( mime_type )	{
		res.set('Content-Type', mime_type);
		if	( mime_type.match(/^text\/(?<type>.+)/) )	{
			content = fs.readFileSync(file_path, 'utf-8');
fork icon1
star icon2
watch icon0

94
95
96
97
98
99
100
101
102
103
// server content
let content = context.fs.readFileSync(filename);

content = handleRangeHeaders(content, req, res);

let contentType = mime.getType(filename) || '';

if (!NonCharsetFileTypes.test(filename)) {
  contentType += '; charset=UTF-8';
}
fork icon0
star icon0
watch icon1

368
369
370
371
372
373
374
375
376
377
    ? payload[1]
    : payload[1].replace("file://", "");
const fileName = trimmedURI.split("/").pop();
formData.append("picture", {
  name: fileName,
  type: mime.getType(trimmedURI),
  uri: trimmedURI,
});

const { data } = await axios.post(
fork icon0
star icon0
watch icon0

8
9
10
11
12
13
14
15
16

formats.forEach(function (format) {
  if (!/^\w+$/.test(format))
    throw new TypeError('Invalid format - must be a word.')

  var type = getType[format] = mime.getType(format)
  if (!type || type === 'application/octet-stream')
    throw new Error('Invalid format.')
})
fork icon0
star icon0
watch icon0

44
45
46
47
48
49
50
51
52
53
 * @param {string} filePath 
 * @returns {MessageMedia}
 */
static fromFilePath(filePath) {
    const b64data = fs.readFileSync(filePath, {encoding: 'base64'});
    const mimetype = mime.getType(filePath); 
    const filename = path.basename(filePath);

    return new MessageMedia(mimetype, b64data, filename);
}
fork icon0
star icon0
watch icon0

202
203
204
205
206
207
208
209
210
211
212
213


  res.setHeader(
    "Content-Disposition",
    `attachment; filename=${fileName}${fileExtension}`
  );
  res.setHeader("Content-Type", mime.getType(filePath));


  const fileStream = fs.createReadStream(filePath);
  fileStream.pipe(res);
});
fork icon0
star icon0
watch icon0

+ 3 other calls in file

42
43
44
45
46
47
48
49
50
51
}

const pathToFile = path.join(staticDir, file);
const staticContent = {
    content: fs.readFileSync(pathToFile),
    contentType: mime.getType(file)
};
const route = rootPath + file;

if (forbiddenRoutes.includes(route)) {
fork icon0
star icon0
watch icon0

15
16
17
18
19
20
21
22
23
24
25
const getMimeType = url => {
    if (url.indexOf('?') !== -1) { // remove url query so we can have a clean extension
        url = url.split("?")[0];
    }
    if (mime.getType(url) === 'application/x-msdownload') return 'text/html';
    return mime.getType(url) || 'text/html'; // if there is no extension return as html
};


app.get('/', (req, res) => {
    const { url } = req.query; // get url parameter
fork icon0
star icon0
watch icon0

34
35
36
37
38
39
40
41
42
43
  });
  res.writeHead(200);
}

let file = __dirname + "/public/" + path;
let contentType = mime.getType(file);

//reading files
fs.readFile(file, (err, data) => {
  if (err) {
fork icon0
star icon0
watch icon0

115
116
117
118
119
120
121
122
123
124
var fstream = fs.createReadStream(file + (isGzip ? '.gz' : ''));
var maxAge = opts.maxAge === undefined ? 3600 : opts.maxAge;
fstream.once('open', function onceOpen(fd) {
    res.cache({ maxAge: maxAge });
    res.set('Content-Length', stats.size);
    res.set('Content-Type', mime.getType(file));
    res.set('Last-Modified', stats.mtime);

    if (opts.charSet) {
        var type =
fork icon0
star icon0
watch icon244