本文整理汇总了TypeScript中mime-types.lookup函数的典型用法代码示例。如果您正苦于以下问题:TypeScript lookup函数的具体用法?TypeScript lookup怎么用?TypeScript lookup使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了lookup函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: detect
export function detect(filename: string=null, buffer: Buffer=null): DetectionResult | null {
if (filename !== null) {
const mimeType = filenameToTextMimetype(filename);
if (mimeType !== null) {
return {mimeType, charset: null };
}
const imageMimeType = mimeTypes.lookup(filename);
if (imageMimeType !== null && imageMimeType !== false) {
return { mimeType: imageMimeType, charset: null };
}
}
// Check the data directly.
if (buffer !== null) {
const fileTypeResult = filetype(buffer);
if (fileTypeResult !== null) {
return {mimeType: fileTypeResult.mime, charset: null };
}
if ( ! isNotText(buffer)) {
const result = jschardet.detect(buffer.slice(0, SAMPLE_SIZE).toString());
if (result.encoding !== null && result.confidence > 0.8) {
return { mimeType: "text/plain", charset: result.encoding };
}
}
}
return { mimeType: "application/octet-stream", charset: null };
}
示例2: getMimeType
export function getMimeType(path: string): string {
let mime = Mime.lookup(path);
if (mime === false) {
mime = "application/octet-stream";
}
return mime;
}
示例3: getContentType
export function getContentType(
inputData: ReadableStream | Buffer | string
): string {
let contentType = null;
if (isFileStream(inputData)) {
// if the inputData is a ReadableStream
const mimeType = lookup(inputData.path);
contentType = { mime: mimeType || null };
} else if (Buffer.isBuffer(inputData)) {
// if the inputData is a Buffer
contentType = fileType(inputData);
} else if (typeof inputData == 'string') {
// if the inputData is a string
contentType = fileType(Buffer.from(inputData));
}
return contentType ? contentType.mime : null;
}
示例4: decodeURI
(request, callback) => {
const urlPath = url.parse(request.url).pathname;
const decodedPath = decodeURI(urlPath);
const rootlessPath = decodedPath.replace(/^\//, "");
const filePath = join(fileRoot, rootlessPath);
try {
var stats = statSync(filePath);
var stream = createReadStream(filePath);
callback({
headers: {
server: "itch",
"content-type": mime.lookup(filePath),
"content-length": stats.size,
"access-control-allow-origin": "*",
},
statusCode: 200,
data: stream as any, // *sigh*
});
} catch (e) {
logger.warn(`while serving ${request.url}, got ${e.stack}`);
let statusCode = 400;
switch (e.code) {
case "ENOENT":
statusCode = 404;
break;
case "EPERM":
statusCode = 401;
break;
}
callback({
headers: {},
statusCode,
data: null,
});
return;
}
},
示例5: async
app.get("/resource/:url(*)", async (req, res) => {
if (!ensureAuthed(req, res)) {
return;
}
try {
const fullPath = `/${req.params.url}`;
// const relative = path.relative(options!.dataDirectory, fullPath);
// if (relative.startsWith("..")) {
// return res.status(403).end();
// }
const exists = fs.existsSync(fullPath);
if (!exists) {
return res.status(404).end();
}
const stat = await util.promisify(fs.stat)(fullPath);
if (!stat.isFile()) {
res.write("Resource must be a file.");
res.status(422);
return res.end();
}
let mimeType = mime.lookup(fullPath);
if (mimeType === false) {
mimeType = "application/octet-stream";
}
const content = await util.promisify(fs.readFile)(fullPath);
res.header("Content-Type", mimeType as string);
res.write(content);
res.status(200);
res.end();
} catch (ex) {
res.write(ex.toString());
res.status(500);
res.end();
}
});
示例6: next
fs.readFile(path.resolve(swaggerUiPath, file), (err, content) => {
if (err) {
return next(new errors.NotFoundError(`File ${file} does not exist`));
}
if (file === 'index.html') {
const isReqSecure = options.forceSecure || req.isSecure();
const jsonFileUrl = `${isReqSecure ? 'https' : 'http'}://${req.headers.host}${publicPath}/swagger.json`;
content = new Buffer(content.toString().replace(
'url: "https://petstore.swagger.io/v2/swagger.json"',
`url: "${jsonFileUrl}"`
));
}
const contentType = mime.lookup(file);
if (contentType !== false) {
res.setHeader('Content-Type', contentType);
}
res.write(content);
res.end();
return next();
});
示例7: stat
stat(wholePath, (error, stats) => {
// The server was stopped before this file was served
if (!this._httpServer) {
return;
}
if (error || !stats.isFile()) {
this.executor.log(`Unable to serve ${wholePath} (unreadable)`);
this._send404(response);
return;
}
this.executor.log(`Serving ${wholePath}`);
const contentType =
lookup(basename(wholePath)) || 'application/octet-stream';
const onEnd = (error?: Error) => {
if (error) {
this.executor.emit(
'error',
new Error(
`Error serving ${wholePath}: ${error.message}`
)
);
} else {
this.executor.log(`Served ${wholePath}`);
}
};
const send = (size: number, data: string | Stream | null) => {
response.writeHead(200, {
'Content-Type': contentType,
'Content-Length': size
});
if (!data) {
response.end();
return;
}
if (typeof data === 'string') {
response.end(data, onEnd);
} else {
data.on('end', () => onEnd());
data.on('error', (error: Error) => {
onEnd(error);
// If the read stream errors, the write stream has to be
// manually closed
response.end();
});
data.pipe(response);
}
};
if (this.executor.shouldInstrumentFile(wholePath)) {
const mtime = stats.mtime.getTime();
const codeCache = this._codeCache!;
const entry = codeCache[wholePath];
if (entry && entry.mtime === mtime) {
send(entry.size, entry.data);
} else {
readFile(wholePath, 'utf8', (error, data) => {
// The server was stopped in the middle of the file read
if (!this._httpServer) {
return;
}
if (error) {
this._send404(response);
return;
}
// Providing `wholePath` to the instrumenter instead of
// a partial filename is necessary because lcov.info
// requires full path names as per the lcov spec
data = this.executor.instrumentCode(data, wholePath);
const size = Buffer.byteLength(data);
codeCache[wholePath] = { mtime, data, size };
send(size, data);
});
}
} else {
send(
stats.size,
omitContent ? null : createReadStream(wholePath)
);
}
});
示例8: stat
stat(wholePath, (error, stats) => {
// The server was stopped before this file was served
if (context.stopped) {
return;
}
if (error || !stats.isFile()) {
executor.log('Unable to serve', wholePath, '(unreadable)');
return next(createError(404, error, { expose: false }));
}
executor.log('Serving', wholePath);
const send = (contentType: string, data: string) => {
response.writeHead(200, {
'Content-Type': contentType,
'Content-Length': Buffer.byteLength(data)
});
response.end(request.method === 'HEAD' ? '' : data, callback);
};
const callback = (error?: Error) => {
if (error) {
executor.emit(
'error',
new Error(`Error serving ${wholePath}: ${error.message}`)
);
} else {
executor.log('Served', wholePath);
}
};
const contentType = lookup(wholePath) || 'application/octet-stream';
const mtime = stats.mtime.getTime();
if (codeCache[wholePath] && codeCache[wholePath].mtime === mtime) {
send(contentType, codeCache[wholePath].data);
} else {
readFile(wholePath, 'utf8', (error, data) => {
// The server was stopped in the middle of the file read
if (context.stopped) {
return;
}
if (error) {
return next(createError(404, error, { expose: false }));
}
// providing `wholePath` to the instrumenter instead of a
// partial filename is necessary because lcov.info requires
// full path names as per the lcov spec
data = executor.instrumentCode(data, wholePath);
codeCache[wholePath] = {
// strictly speaking mtime could reflect a previous
// version, assume those race conditions are rare
mtime,
data
};
send(contentType, data);
});
}
});
示例9: _handleFile
private _handleFile(
request: IncomingMessage,
response: ServerResponse,
shouldInstrument?: boolean,
omitContent?: boolean
) {
function send(contentType: string, data: string) {
response.writeHead(200, {
'Content-Type': contentType,
'Content-Length': Buffer.byteLength(data)
});
response.end(data);
}
const file = /^\/+([^?]*)/.exec(request.url)[1];
let wholePath: string;
this.executor.log('Request for', file);
if (/^__intern\//.test(file)) {
wholePath = join(this.executor.config.internPath, file.replace(/^__intern\//, ''));
shouldInstrument = false;
}
else {
wholePath = resolve(join(this.basePath, file));
}
wholePath = normalizePath(wholePath);
if (wholePath.charAt(wholePath.length - 1) === '/') {
wholePath += 'index.html';
}
// if the string passed to `excludeInstrumentation` changes here, it must also change in
// `lib/executors/Executor.js`
if (
this.excludeInstrumentation === true ||
(this.excludeInstrumentation && this.excludeInstrumentation.test(file))
) {
shouldInstrument = false;
}
const contentType = lookup(basename(wholePath)) || 'application/octet-stream';
stat(wholePath, (error, stats) => {
// The server was stopped before this file was served
if (!this.server) {
return;
}
if (error || !stats.isFile()) {
this.executor.log('Unable to serve', wholePath);
this._send404(response);
return;
}
this.executor.log('Serving', wholePath);
if (shouldInstrument) {
const mtime = stats.mtime.getTime();
if (this._codeCache[wholePath] && this._codeCache[wholePath].mtime === mtime) {
send(contentType, this._codeCache[wholePath].data);
}
else {
readFile(wholePath, 'utf8', (error, data) => {
// The server was stopped in the middle of the file read
if (!this.server) {
return;
}
if (error) {
this._send404(response);
return;
}
// providing `wholePath` to the instrumenter instead of a partial filename is necessary because
// lcov.info requires full path names as per the lcov spec
data = instrument(
data,
wholePath,
this.instrumenterOptions
);
this._codeCache[wholePath] = {
// strictly speaking mtime could reflect a previous version, assume those race conditions are rare
mtime: mtime,
data: data
};
send(contentType, data);
});
}
}
else {
response.writeHead(200, {
'Content-Type': contentType,
'Content-Length': stats.size
});
if (omitContent) {
response.end();
}
else {
//.........这里部分代码省略.........
示例10:
import * as mime from 'mime-types';
mime.lookup('json'); // 'application/json'
mime.lookup('.md'); // 'text/x-markdown'
mime.lookup('file.html'); // 'text/html'
mime.lookup('folder/file.js'); // 'application/javascript'
mime.lookup('folder/.htaccess'); // false
mime.lookup('cats'); // false
mime.contentType('markdown'); // 'text/x-markdown; charset=utf-8'
mime.contentType('file.json'); // 'application/json; charset=utf-8'
// from a full path
mime.contentType('.json'); // 'application/json; charset=utf-8'
mime.extension('application/octet-stream'); // 'bin'
mime.charset('text/x-markdown'); // 'UTF-8'