How to use the mime.getType function in mime

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 OpenTMI / opentmi / app / controllers / builds.js View on Github external
.then((file) => {
        // Set correct headers
        const headers = {
          'Content-Type': mime.getType(file.name),
          'Content-disposition': `attachment;filename=${file.name}`,
          'Content-Length': file.data.length
        };

        if (file.encoding !== 'raw') {
          headers['Content-Encoding'] = file.encoding;
        }

        // Write header and send data
        res.writeHead(200, headers);
        res.end(file.data);
      })
      .catch((_error) => {
github careteenL / webpack-hmr / dev-server.js View on Github external
function middleware(req, res, next) {
      if (req.url === '/favicon.ico') {
        return res.sendStatus(404)
      }
      // /index.html   dist/index.html
      let filename = path.join(config.output.path, req.url.slice(1))
      let stat = fs.statSync(filename)
      if (stat.isFile()) { // 判断是否存在这个文件,如果在的话直接把这个读出来发给浏览器
        let content = fs.readFileSync(filename)
        let contentType = mime.getType(filename)
        res.setHeader('Content-Type', contentType)
        res.statusCode = res.statusCode || 200
        res.send(content)
      } else {
        // next()
        return res.sendStatus(404)
      }
    }
    // express app  其实是一个请求监听函数
github ondras / cfo / viewer / text / viewer.js View on Github external
function getType(str) {
		let mt = mime.getType(str);
		if (mt) { return mt; }

		if (str.match(/\.py$/i)) { return "text/x-python"; }

		return "file";
	}
github trayio / falafel / lib / fileHandler / index.js View on Github external
return when.promise(function (resolve, reject) {

			//Generate a random file name
			const fileGuidName = guid();

			//Get mimeType
			const mimeType = params.contentType || mime.getType(params.name);

			const uploadParams = {
				Bucket: params.bucket || TARGET_BUCKET,
				Key: fileGuidName,
				ContentType: mimeType
			};

			const uploadOptions = {
				partSize: UPLOAD_MIN_SIZE, //default 8MB parts
				queueSize: 4 //default 4 parallel uploads
			};
			if (!_.isUndefined(params.length)) {
				const fileSize = uploadParams.ContentLength = params.length;

				if (fileSize > UPLOAD_MIN_SIZE) {
					uploadOptions.partSize = TARGET_SIZE;
github mihhail-lapushkin / grunt-css-url-embed / tasks / css-url-embed.js View on Github external
function resolveMimeTypeEmbedUrlAndGoToNext(url, urlContent, fileContent, nextUrl, options) {
    var urlContentInBuffer = new Buffer(urlContent);
    
    if (mmmagicMimeType && options.useMimeTypeSniffing) {
      mmmagicMimeType.detect(urlContentInBuffer, function(error, mimeType) {
        if (error) {
          mimeType = 'application/octet-stream';
          grunt.log.warn('Failed to get MIME-type of "' + url + '". Defaulting to "' + mimeType + '".');
        }
        
        embedUrlAndGoToNext(url, urlContentInBuffer, mimeType, fileContent, nextUrl);
      });
    } else {
      embedUrlAndGoToNext(url, urlContentInBuffer, mime.getType(url), fileContent, nextUrl);
    }
  }
github qiu8310 / minapp / packages / compiler / src / plugin / postcss-assets.ts View on Github external
data: async (loader, [imageFile]) => {
    let mediaType = mime.getType(imageFile)
    let buffer = await readFile(imageFile)
    return `url(data:${mediaType};${encodeBuffer(buffer, mediaType)})`
  },
github QuickCorp / QCObjects / node_modules / qcobjects-cli / org.quickcorp.qcobjects.main.file.js View on Github external
appTemplateInstance.template = data.toString();
            appTemplateInstance._done.call(appTemplateInstance);
          } else {
            appTemplateInstance.headers = {
              ':status': 404,
              'content-type': 'text/html'
            };
            appTemplateInstance.done.call(appTemplateInstance,
                                          appTemplateInstance.headers,
                                          'FILE NOT FOUND','notfound.html',false);
            logger.debug('file not found');
          }
        });
      } else {
        appTemplateInstance.headers[':status']=200;
        appTemplateInstance.headers['content-type']=mime.getType(appTemplateInstance.templateURI);
        appTemplateInstance.done.call(appTemplateInstance,
                                      appTemplateInstance.headers,
                                      '',appTemplateInstance.templateURI,false);
      }

      logger.info('FileDispatcher initialized');
    }
  })