How to use mime - 10 common examples

To help you get started, we’ve selected a few mime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rollup / plugins / packages / url / src / index.js View on Github external
.split(sep)
                .pop();

          // Generate the output file name based on some string
          // replacement parameters
          const outputFileName = fileName
            .replace(/\[hash\]/g, hash)
            .replace(/\[extname\]/g, ext)
            // use `sep` for windows environments
            .replace(/\[dirname\]/g, `${relativeDir}${sep}`)
            .replace(/\[name\]/g, name);
          // Windows fix - exports must be in unix format
          data = `${publicPath}${outputFileName.split(sep).join(posix.sep)}`;
          copies[id] = outputFileName;
        } else {
          const mimetype = mime.getType(id);
          const isSVG = mimetype === 'image/svg+xml';
          data = isSVG ? encodeSVG(buffer) : buffer.toString('base64');
          const encoding = isSVG ? '' : ';base64';
          data = `data:${mimetype}${encoding},${data}`;
        }
        return `export default "${data}"`;
      });
    },
github CartoDB / airship / scripts / release-s3.js View on Github external
async function uploadFile ({ filePath, dst }, destination, copyVersions) {
  const extension = path.extname(filePath);
  const objectConfig = {
    ACL: 'public-read',
    Bucket: secrets.AWS_S3_BUCKET
  };
  let fileLength = 0; // uncompressed size
  let fileContent;
  let ratio = 0;

  objectConfig.ContentType = `${mime.getType(filePath)}${needsUTF8(extension) ? '; charset=utf-8' : ''}`;

  try {
    fileContent = await readFile(filePath, needsUTF8(extension) ? { encoding: 'utf8' } : {});
    fileLength = fileContent.length;

    if (shouldZip(extension)) {
      fileContent = await gzip(fileContent);
      objectConfig.ContentEncoding = 'gzip';
    }

    objectConfig.Body = fileContent;

    ratio = Math.round((fileContent.length / fileLength) * 100);
  } catch (e) {
    console.error(e);
    return;
github expo / expo-cli / packages / webpack-pwa-manifest-plugin / src / icons.ts View on Github external
async function processImageAsync(
  size: AnySize,
  icon: Icon,
  publicPath: string,
  cacheKey: string
): Promise<{ manifestIcon: ManifestIcon; webpackAsset: WebpackAsset }> {
  const { width, height } = toSize(size);
  if (width <= 0 || height <= 0) {
    throw Error(`Failed to process image with invalid size: { width: ${width}, height: ${height}}`);
  }
  const mimeType = mime.getType(icon.src);
  if (!mimeType) {
    throw new Error(`Invalid mimeType for image with source: ${icon.src}`);
  }

  const dimensions = `${width}x${height}`;
  const fileName = `icon_${dimensions}.${mime.getExtension(mimeType)}`;

  let imageBuffer: Buffer | null = await getImageFromCacheAsync(fileName, cacheKey);
  if (!imageBuffer) {
    // Putting the warning here will prevent the warning from showing if all images were reused from the cache
    if (!hasWarned && !(await isAvailableAsync())) {
      hasWarned = true;
      // TODO: Bacon: Fallback to nodejs image resizing as native doesn't work in the host environment.
      console.log('ff', cacheKey, fileName, dimensions);
      console.log();
      console.log(
github jfremy / plexjs / node_modules / connect / lib / middleware / static.js View on Github external
// redirect directory in case index.html is present
    } else if (stat.isDirectory()) {
      if (!redirect) return next();
      url = parse(req.originalUrl);
      res.statusCode = 301;
      res.setHeader('Location', url.pathname + '/');
      res.end('Redirecting to ' + url.pathname + '/');
      return;
    }

    // header fields
    if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString());
    if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000));
    if (!res.getHeader('Last-Modified')) res.setHeader('Last-Modified', stat.mtime.toUTCString());
    if (!res.getHeader('Content-Type')) {
      var charset = mime.charsets.lookup(type);
      res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
    }
    res.setHeader('Accept-Ranges', 'bytes');

    // conditional GET support
    if (utils.conditionalGET(req)) {
      if (!utils.modified(req, res)) {
        req.emit('static');
        return utils.notModified(res);
      }
    }

    var opts = {}
      , len = stat.size;

    // we have a Range request
github patrickleet / bootstrap-override-boilerplate / theme-name / node_modules / connect / lib / middleware / static.js View on Github external
: next(err);
    // redirect directory in case index.html is present
    } else if (stat.isDirectory()) {
      if (!redirect) return next();
      res.statusCode = 301;
      res.setHeader('Location', url.pathname + '/');
      res.end('Redirecting to ' + url.pathname + '/');
      return;
    }

    // header fields
    if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString());
    if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000));
    if (!res.getHeader('Last-Modified')) res.setHeader('Last-Modified', stat.mtime.toUTCString());
    if (!res.getHeader('Content-Type')) {
      var charset = mime.charsets.lookup(type);
      res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
    }
    res.setHeader('Accept-Ranges', 'bytes');

    // conditional GET support
    if (utils.conditionalGET(req)) {
      if (!utils.modified(req, res)) {
        req.emit('static');
        return utils.notModified(res);
      }
    }

    var opts = {}
      , len = stat.size;

    // we have a Range request
github beakerbrowser / beaker / app / background-process / ui / downloads.js View on Github external
const listener = async (e, item, wc) => {
    // dont touch if already being handled
    // - if `opts.saveAs` is being used, there may be multiple active event handlers
    if (item.isHandled) { return }

    // build a path to an unused name in the downloads folder
    let filePath = opts.saveAs ? opts.saveAs : unusedFilename.sync(path.join(app.getPath('downloads'), item.getFilename()))

    // track as an active download
    item.id = ('' + Date.now()) + ('' + Math.random()) // pretty sure this is collision proof but replace if not -prf
    item.name = path.basename(filePath)
    if (item.name.split('.').length < 2 && item.getMimeType()) {
      const ext = `.${mime.extension(item.getMimeType())}`
      if (ext !== '.bin') {
        item.name += ext
        filePath += ext
      }
    }
    item.setSavePath(filePath)
    item.isHandled = true
    item.downloadSpeed = speedometer()

    if (!opts.trusted) {
      item.pause()
      var allowed = await requestPermission('download', wc, {url: item.getURL(), filename: item.name})
      if (!allowed) {
        item.cancel()
        return
      }
github ccampbell / cloud-storage / storage.js View on Github external
if (progressStream) {
            stream = stream.pipe(progressStream);
        }

        var headers = {
            'Content-Length': stat.size,
            'Content-Type': mime.lookup(path.path || path),
            'Cache-Control': 'public, max-age=3600, no-transform',
            'X-Goog-Acl': 'public-read'
        };

        // missing extension on destination
        // use the source or the content type
        if (options.forceExtension && destination.split('/').pop().split('.').length === 1) {
            var fileName = (path.path || path).split('/').pop();
            var extension = fileName.indexOf('.') ? fileName.split('.').pop() : mime.extension(headers['Content-Type']);
            destination += '.' + extension;
        }

        var key;
        if (options.hasOwnProperty('headers')) {
            for (key in options.headers) {
                if (options.headers.hasOwnProperty(key)) {
                    headers[key] = options.headers[key];
                }
            }
        }

        if (options.hasOwnProperty('metadata')) {
            for (key in options.metadata) {
                if (options.metadata.hasOwnProperty(key)) {
                    headers['X-Goog-Meta-' + key] = options.metadata[key];
github kapouer / url-inspector / lib / inspector.js View on Github external
function normalize(obj) {
	// remove all empty keys
	Object.keys(obj).forEach(function(key) {
		var val = obj[key];
		if (val == "" || val == null || (typeof val == 'number' && isNaN(val))) delete obj[key];
	});

	if (!obj.ext) {
		if (obj.mime) {
			obj.ext = mime.getExtension(obj.mime);
			if (!obj.ext) {
				// eslint-disable-next-line no-console
				console.warn("No extension found for mime type", obj.mime, obj.url);
			}
		}
		if (!obj.ext) {
			// eslint-disable-next-line no-console
			console.warn("Using extname", obj.pathname);
			obj.ext = Path.extname(obj.pathname).substring(1);
		}
	}
	delete obj.pathname;
	if (obj.ext) {
		obj.ext = obj.ext.toLowerCase();
		switch (obj.ext) {
			case "jpeg":
github expo / expo-cli / packages / webpack-pwa-manifest-plugin / src / icons.ts View on Github external
size: AnySize,
  icon: Icon,
  publicPath: string,
  cacheKey: string
): Promise<{ manifestIcon: ManifestIcon; webpackAsset: WebpackAsset }> {
  const { width, height } = toSize(size);
  if (width <= 0 || height <= 0) {
    throw Error(`Failed to process image with invalid size: { width: ${width}, height: ${height}}`);
  }
  const mimeType = mime.getType(icon.src);
  if (!mimeType) {
    throw new Error(`Invalid mimeType for image with source: ${icon.src}`);
  }

  const dimensions = `${width}x${height}`;
  const fileName = `icon_${dimensions}.${mime.getExtension(mimeType)}`;

  let imageBuffer: Buffer | null = await getImageFromCacheAsync(fileName, cacheKey);
  if (!imageBuffer) {
    // Putting the warning here will prevent the warning from showing if all images were reused from the cache
    if (!hasWarned && !(await isAvailableAsync())) {
      hasWarned = true;
      // TODO: Bacon: Fallback to nodejs image resizing as native doesn't work in the host environment.
      console.log('ff', cacheKey, fileName, dimensions);
      console.log();
      console.log(
        chalk.bgYellow.black(
          `PWA Images: Using node to generate images. This is much slower than using native packages.`
        )
      );
      console.log(
        chalk.yellow(
github lbryio / lbry-desktop / src / ui / util / get-media-type.js View on Github external
export default function getMediaType(contentType, fileName) {
  const extName = mime.getExtension(contentType);
  const fileExt = extName ? `.${extName}` : null;
  const testString = fileName || fileExt;

  // Get mediaType from file extension
  if (testString) {
    const res = formats.reduce((ret, testpair) => {
      const [regex, mediaType] = testpair;

      return regex.test(ret) ? mediaType : ret;
    }, testString);

    if (res !== testString) return res;
  }

  // Get mediaType from contentType
  if (contentType) {