is-valid-mime

Returns true if the string corresponds to a valid MIME type.

Usage no npm install needed!

<script type="module">
  import isValidMime from 'https://cdn.skypack.dev/is-valid-mime';
</script>

README

isValidMime

Returns true if the string corresponds to a valid MIME type.

Build Status codecov Maintainability

Summary

About

I created this package to have a straight forward way to check if a MIME type is valid in my code.

Note that if you do not want to pull a dependency, here is how you can do it without this package:

import mimeDb from "mime-db";

const mimeType = "text/html";

if (mimeType in mimeDb) {
  console.log(`${mimeType} is a valid MIME type`);
} else {
  console.log(`${mimeType} is not a valid MIME type`);
}

This package provides its own Typescript definition.

Features

  • Returns true if the mime passed in parameter is valid, else returns false

Requirements

NPM or Yarn installed on your machine.

Installation

Using NPM

npm install is-valid-mime

Using Yarn

yarn add is-valid-mime

Examples

1. Getting started

In this example, you will see how to check if a variable is a valid mime type.

import isValidMime from "is-valid-mime";

const mimeType = "cats";

if (isValidMime(mimeType)) {
  console.log("valid");
} else {
  console.log("not valid");
}

2. Catch errors

In this example, you will see how to catch errors that are thrown by this function.

import isValidMime from "is-valid-mime";

const mimeType = 42;
let valid = false;

try {
  valid = isValidMime(mimeType);
} catch (exception) {
  if (exception instanceof TypeError) {
    console.log("expected isValidMime to be called with a string parameter");
  } else {
    console.log("Unhandled error happened");
  }
}

if (valid) {
  console.log("valid");
} else {
  console.log("not valid");
}

API

const isValidMime = (mime: string): boolean;

Exceptions

  • TypeError: if the first parameter is not a string.