How to use the mime.extension 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 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 NREL / api-umbrella / lib / gatekeeper / utils.js View on Github external
// Fall back to a GET parameter named "format".
  if(mimeType === 'application/octet-stream' && request.query.format) {
    mimeType = mime.lookup(request.query.format.toString());
  }

  // Failing that, use Accept header negotiation.
  if(mimeType === 'application/octet-stream') {
    var negotiator = new Negotiator(request);
    mimeType = negotiator.preferredMediaType(availableMediaTypes);
  }

  if(mimeType === 'application/octet-stream' || availableMediaTypes.indexOf(mimeType) === -1) {
    mimeType = availableMediaTypes[0];
  }

  var format = mime.extension(mimeType);

  var settings;
  if(request.apiUmbrellaGatekeeper && request.apiUmbrellaGatekeeper.settings) {
    settings = request.apiUmbrellaGatekeeper.settings;
  } else {
    settings = config.get('apiSettings');
  }

  // Strip leading and trailing whitespace from template, since it's easy to
  // introduce in multi-line templates and XML doesn't like if there's any
  // leading space before the XML declaration.
  var templateContent = settings.error_templates[format].replace(/^\s+|\s+$/g, '');
  var errorData = settings.error_data[error];
  if(!errorData || !_.isPlainObject(errorData)) {
    errorData = settings.error_data.internal_server_error;
    logger.error({ error_type: error }, 'Error data not found for error type: ' + error);
github DefinitelyTyped / DefinitelyTyped / types / mime / mime-tests.ts View on Github external
import * as mime from "mime";

let str: string;
const obj: {} = {};
const fallback: string = '';

str = mime.lookup(str, fallback);
str = mime.extension(str);
mime.load(str);
mime.define(obj);

str = mime.charsets.lookup(str);
github srveit / mechanize-js / lib / mechanize / agent.js View on Github external
logPage = async ({body, uri, response}) => {
      const contentType = response.headers['content-type'],
        ext = mime.extension(contentType &&
                                 contentType.split(/[ \t]*;[ \t]*/)[0]),
        timestamp = moment.utc().format('YYYYMMDDHHmmssSSSSSS'),
        filename = path.join(
          logDir,
          timestamp + '_' +
            path.basename(uri, path.extname(uri))) +
              (ext ? '.' + ext : ''),
        encoding = 'utf8';

      await writeFile(filename, body, {encoding});
      return filename;
    },
github iolo / pictor / routes / api.js View on Github external
function _getFileId(id, prefix, type) {
    if (!id) {
        throw 'required_param_id';
    }
    if (id === ID_NEW) {
        return _generateUniqueId(prefix || DEF_PREFIX, type ? '.' + mime.extension(type) : DEF_SUFFIX);
    }
    if (ID_REGEX.test(id)) {
        return id;
    }
    throw 'invalid_param_id';
}
github andris9 / resolver / lib / resolver.js View on Github external
(meta.responseHeaders['content-disposition'] || '').split(';').forEach(function(line) {
        var parts = line.trim().split('='),
            key = parts.shift().toLowerCase().trim();
        if (key == 'filename') {
            filename = parts.join('=').trim();
        }
    });

    if (contentType == 'application/octet-stream') {
        contentType = mime.lookup(filename) || 'application/octet-stream';
    } else {
        fileParts = filename.split('.');
        if (fileParts.length > 1) {
            extension = fileParts.pop().toLowerCase();
        }
        contentExtension = mime.extension(contentType);
        if (contentExtension && extension != contentExtension) {
            extension = contentExtension;
        }
        if (extension) {
            if (!fileParts.length ||  (fileParts.length == 1 && !fileParts[0])) {
                fileParts = ['index'];
            }
            fileParts.push(extension);
        }
        filename = fileParts.join('.');
    }

    return {
        filename: filename,
        contentType: contentType
    };
github lovetheory / nkc2 / nkc_modules / api_resources_handlers.js View on Github external
api.post('/resources', upload.single('file'), function (req, res, next) {
  if(!req.user) return next('who are you? log in first.');
  if(!req.file) return next('shit not even a file. fuck.')

  var file = req.file
  var originalName = file.originalname
  var size = file.size
  var tempFilePath = file.path
  var mimetype = file.mimetype

  var extension = nkcfs.getExtensionFromFileName(originalName)
  if(!extension)extension = require('mime').extension(mimetype)||null

  Promise.resolve()
  .then(()=>{
    //obtain user first
    if(!req.user) throw('who are you? log in first.');
    if(!req.file) throw('shit not even a file. fuck.')

    if(['jpg','jpeg','png'].indexOf(extension)>=0)//if is processable image
    {
      if(size>settings.size_largeimage){ //if file larger than specified size
        return im.attachify(tempFilePath)
      }
      //if not really large
      else {
        return im.info(tempFilePath)
        .then(info=>{
github botgram / shell-bot / lib / utils.js View on Github external
function constructFilename(msg) {
  return "upload." + mime.extension(msg.file.mime);
}