Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'mime-types' 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.
// --ipfs-api option
const IPFS = require('ipfs-http-client')
const addr = multiaddr(argv['ipfs-api'])
const nodeAddress = addr.nodeAddress()
ipfs = new IPFS(nodeAddress.address, nodeAddress.port)
} else {
const IPFS = require('ipfs')
ipfs = await IPFS.create({ start: false })
}
} catch (e) {
console.error(e)
throw new Error('Please use npm to install either `ipfs` or `ipfs-http-client`.')
}
// Register new MIME type for .ambient files
mime.extensions['text/ambients'] = ['ambient']
mime.types.ambient = 'text/ambients'
const file = fs.readFileSync(argv.input).toString().trim()
let result
switch (mime.lookup(argv.input)) {
case 'application/javascript':
result = await output(ipfs, file, argv); break
case 'text/ambients':
result = await output(ipfs, file, argv); break
default:
throw new Error('File type not recognized')
}
process.stdout.write(result + '\n')
process.exit(0)
const IPFS = require('ipfs-http-client')
const addr = multiaddr(argv['ipfs-api'])
const nodeAddress = addr.nodeAddress()
ipfs = new IPFS(nodeAddress.address, nodeAddress.port)
} else {
const IPFS = require('ipfs')
ipfs = await IPFS.create({ start: false })
}
} catch (e) {
console.error(e)
throw new Error('Please use npm to install either `ipfs` or `ipfs-http-client`.')
}
// Register new MIME type for .ambient files
mime.extensions['text/ambients'] = ['ambient']
mime.types.ambient = 'text/ambients'
const file = fs.readFileSync(argv.input).toString().trim()
let result
switch (mime.lookup(argv.input)) {
case 'application/javascript':
result = await output(ipfs, file, argv); break
case 'text/ambients':
result = await output(ipfs, file, argv); break
default:
throw new Error('File type not recognized')
}
process.stdout.write(result + '\n')
process.exit(0)
})(argv)
for (var i = 0, len = resources.length; i < len; i++) {
var resource = resources[i];
var type = resource.type;
if (type == mime.contentType('css')) {
var style = document.createElement('style');
style.innerHTML = resource.body;
head.appendChild(style);
//todo font loading
// var font = new FontFaceObserver('Conv_interdex');
// font.load().then(function () {
//
// });
} else if (type == mime.contentType('js')) {
scripts += ' ' + resource.body + ';';
}
}
var err = null;
try {
var script = new vm.VM({
timeout: 5000,
sandbox: window
});
script.run(scripts);
} catch (e) {
console.log(e);
err = e;
}
app.get(`/resources/:id/download/:f?`, async function(req, res) {
let resource
try {
resource = await db.Resource.findById(req.params.id)
} catch(err){
console.log(err)
res.status(404).render('404', {
user: req.session.user,
csrfToken: req.csrfToken()
})
return
}
if(!req.params.f) {
let title = resource.name.replace(/\ /g, '-')
let type = require('mime-types').extension(resource.type) || 'mp3'
let f = `${sanitize(title)}.${type}`
res.redirect(`/resources/${req.params.id}/download/${f}`)
} else {
try {
await resource.incrementDownloads(req.ip)
for(let owner of resource.owners) {
let u = await User.findByUsername(owner)
if(owner != req.session.user)
u.sendMessage('download', 'resource', 'Resource', resource._id, 1)
}
} catch(err){
console.log(err)
// continue to download anyway
}
if(resource.script) {
UploadFileField.prototype.toJavaScript = function (uploadedFile) {
if (uploadedFile) {
if (this.widget && this.widget.attrs.maxSize && uploadedFile.size > this.widget.attrs.maxSize) {
var maxSizeInMB = utils._.round(this.widget.attrs.maxSize / (1024 * 1024), 2);
throw newforms.ValidationError(this.errorMessages.maxSize, {code:"maxLength", params: {maxSizeInMB: maxSizeInMB}});
}
if (this.widget && this.widget.attrs.accept) {
var extension = "";
/* recuperation de l'extension du fichier */
/* par défaut, on recupere celle qui est associée au mime type : */
if (uploadedFile.type) {
extension = mime.extension(uploadedFile.type);
}
/* par contre, si l'extension est présente dans le nom du fichier */
/* on la prend en priorité : */
if (uploadedFile.name && uploadedFile.name.indexOf(".") != -1) {
extension = utils._.last(uploadedFile.name.split("."));
}
/* comparaison de l'extension du fichier avec la liste des extensions autorisées (accept) */
/* _.some renvoie true si au moins une des extensions autorisées correspond */
var allowedType = utils._.some(this.widget.attrs.accept, function (accept) {
return accept === "." + extension
});
if (!allowedType) {
throw newforms.ValidationError(this.errorMessages.invalid, {code: "invalid", params: {fileTypeList:this.widget.attrs.accept}});
}
}
if (contentType) {
contentType = contentType.toLowerCase();
if (cardContentTypes[contentType])
contentType = cardContentTypes[contentType];
}
else {
contentType = mime.lookup(contentUrl) || cardContentTypes[path.extname(contentUrl)];
if (!contentType && contentUrl && contentUrl.indexOf('http') == 0) {
let options = { method: 'HEAD', uri: contentUrl };
let response = await request(options);
contentType = response['content-type'].split(';')[0];
}
}
const charset = mime.charset(contentType);
// if not a url
if (contentUrl.indexOf('http') != 0) {
// read the file
let content = await readAttachmentFile(contentUrl, contentType);
// if it is not a card
if (!isCard(contentType) && charset !== 'UTF-8') {
// send as base64
contentUrl = `data:${contentType};base64,${new Buffer(content).toString('base64')}`;
content = undefined;
} else {
contentUrl = undefined;
}
return (activity.attachments || (activity.attachments = [])).push(new Attachment({ contentType, contentUrl, content }));
}
// send as contentUrl
if (resHeaders.error) {
req.emit('error', resHeaders.error);
return;
}
var res = new http.IncomingMessage(socket);
res.headers = resHeaders.headers || {};
res.statusCode = resHeaders.statusCode;
if (callback) {
callback(res);
}
if (!forceLive) {
var isBinary = !mimeTypes.charset(resHeaders['content-encoding']);
resBody = isBinary ?
fs.readFileSync(filename) :
replayerUtil.substituteWithRealValues(fs.readFileSync(filename).toString());
}
req.emit('response', res);
if (res.push) {
// node 0.10.x
res.push(resBody);
res.push(null);
} else {
// node 0.8.x
res.emit('data', resBody);
res.emit('end');
}
const M3U8Parse = require('m3u8parse');
const Oncemore = require('oncemore');
const UriStream = require('uristream');
const Readable = require('readable-stream');
const SegmentFetcher = require('./segment-fetcher');
const HlsSegmentObject = require('./segment-object');
try {
const MimeTypes = require('mime-types');
/* eslint-disable dot-notation */
MimeTypes.types['ac3'] = 'audio/ac3';
MimeTypes.types['eac3'] = 'audio/eac3';
MimeTypes.types['m4s'] = 'video/iso.segment';
/* eslint-enable dot-notation */
}
catch (err) {
console.error('Failed to inject extra types', err);
}
const internals = {
indexMimeTypes: new Set([
'application/vnd.apple.mpegurl',
'application/x-mpegurl',
'audio/mpegurl'
]),
segmentMimeTypes: new Set([
'video/mp2t',
'video/mpeg',
'video/mp4',
const Url = require('url');
const M3U8Parse = require('m3u8parse');
const Oncemore = require('oncemore');
const UriStream = require('uristream');
const Readable = require('readable-stream');
const SegmentFetcher = require('./segment-fetcher');
const HlsSegmentObject = require('./segment-object');
try {
const MimeTypes = require('mime-types');
/* eslint-disable dot-notation */
MimeTypes.types['ac3'] = 'audio/ac3';
MimeTypes.types['eac3'] = 'audio/eac3';
MimeTypes.types['m4s'] = 'video/iso.segment';
/* eslint-enable dot-notation */
}
catch (err) {
console.error('Failed to inject extra types', err);
}
const internals = {
indexMimeTypes: new Set([
'application/vnd.apple.mpegurl',
'application/x-mpegurl',
'audio/mpegurl'
]),
segmentMimeTypes: new Set([
'video/mp2t',
'video/mpeg',
// eslint-disable-next-line no-unused-vars
import {h} from 'preact';
import path from 'path';
import mime from 'mime-types';
mime.types.ts = 'application/typescript';
// eslint-disable-next-line no-unused-vars
import {Controlled as CodeMirror} from 'react-codemirror2';
import 'codemirror/mode/jsx/jsx.js';
import 'codemirror/mode/css/css.js';
import 'codemirror/mode/htmlmixed/htmlmixed.js';
import 'codemirror/mode/yaml/yaml.js';
import 'codemirror/mode/toml/toml.js';
import 'codemirror/mode/markdown/markdown.js';
import 'codemirror/lib/codemirror.css';
function patchMime(v) {
if (/(?:application|text)\/javascript/.test(v)) return 'text/jsx';
else if (v === 'text/less') return 'text/x-less';
else return v;