當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript mime-types.lookup函數代碼示例

本文整理匯總了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 };
}
開發者ID:sedwards2009,項目名稱:extraterm,代碼行數:30,代碼來源:MimeTypeDetector.ts

示例2: getMimeType

export function getMimeType(path: string): string {
    let mime = Mime.lookup(path);
    if (mime === false) {
        mime = "application/octet-stream";
    }
    return mime;
}
開發者ID:kildevaeld,項目名稱:assets,代碼行數:7,代碼來源:utils.ts

示例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;
}
開發者ID:jpdjere,項目名稱:MinCyT,代碼行數:17,代碼來源:helper.ts

示例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;
        }
      },
開發者ID:itchio,項目名稱:itch,代碼行數:39,代碼來源:itch-cave-protocol.ts

示例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();
		}
	});
開發者ID:AhmadAlyTanany,項目名稱:code-server,代碼行數:38,代碼來源:server.ts

示例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();
        });
開發者ID:RemyJeancolas,項目名稱:restify-swagger-jsdoc,代碼行數:23,代碼來源:index.ts

示例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)
				);
			}
		});
開發者ID:jason0x43,項目名稱:intern,代碼行數:90,代碼來源:Server.ts

示例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);
        });
      }
    });
開發者ID:edhager,項目名稱:intern,代碼行數:61,代碼來源:instrument.ts

示例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 {
//.........這裏部分代碼省略.........
開發者ID:bryanforbes,項目名稱:intern,代碼行數:101,代碼來源:Server.ts

示例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'
開發者ID:AbraaoAlves,項目名稱:DefinitelyTyped,代碼行數:18,代碼來源:mime-types-tests.ts


注:本文中的mime-types.lookup函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。