Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'mime' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
.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}"`;
});
},
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;
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(
// 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
: 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
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
}
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];
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":
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(
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) {