当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript mime.getType函数代码示例

本文整理汇总了TypeScript中mime.getType函数的典型用法代码示例。如果您正苦于以下问题:TypeScript getType函数的具体用法?TypeScript getType怎么用?TypeScript getType使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了getType函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1:

 const images = files.filter(file => {
   const type = mime.getType(file);
   if (!type) {
     return false;
   }
   return type.startsWith('image');
 });
开发者ID:screendriver,项目名称:redater,代码行数:7,代码来源:redater.ts

示例2: pushResources

export function pushResources(
    options: ServerOptions, req: express.Request, res: Response) {
  if (res.push && options.protocol === 'h2' && options.pushManifestPath &&
      !req.get('x-is-push')) {
    // TODO: Handle preload link headers
    const pushManifest =
        getPushManifest(options.root, options.pushManifestPath);
    const resources = pushManifest[req.path];
    if (resources) {
      const root = options.root;
      for (const filename of Object.keys(resources)) {
        const stream = res.push(filename, {
                            request: {accept: '*/*'},
                            response: {
                              'content-type': mime.getType(filename),

                              // Add an X-header to the pushed request so we
                              // don't trigger pushes for pushes
                              'x-is-push': 'true'
                            }
                          })
                           .on('error',
                               (err: {}) => console.error(
                                   'failed to push', filename, err));
        fs.createReadStream(path.join(root, filename)).pipe(stream);
      }
    }
  }
}
开发者ID:poehlmann,项目名称:EvaluacionDiferencialDeLaMemoria,代码行数:29,代码来源:push.ts

示例3: download_file

function download_file(req: express.Request, res: express.Response){
	let file = paths.projects+req.query.project+'/'+req.query.file;
	res.setHeader('Content-disposition', 'attachment; filename='+req.query.file);
	res.setHeader('Content-type', mime.getType(file));
	// this should really go through the file_manager lock - TODO
	fs.createReadStream(file).pipe(res);
}
开发者ID:BelaPlatform,项目名称:Bela,代码行数:7,代码来源:RouteManager.ts

示例4: routeStatic

function routeStatic(req, res, connectionType, buildType) {
    const ROOTS = [join(__dirname, '..')];
    if (buildType !== 'dev') {
        ROOTS.push(join(__dirname, `../dist/build/${connectionType}/${buildType}`));
    } else {
        ROOTS.push(join(__dirname, '../src'));
    }

    const [url] = req.url.split('?');
    const contentType = getType(url);

    const check = (root: string) => {
        const path = join(root, url);
        readFile(path).then((file: Buffer) => {
            res.setHeader('Cache-Control', 'public, max-age=31557600');
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(file);
        })
            .catch(() => {
                if (ROOTS.length) {
                    check(ROOTS.pop());
                } else {
                    res.writeHead(404, { 'Content-Type': 'text/plain' });
                    res.end('404 Not Found\n');
                }
            });
    };

    check(ROOTS.pop());
}
开发者ID:beregovoy68,项目名称:WavesGUI,代码行数:30,代码来源:utils.ts

示例5: deleteFile

    deleteFile(blog: Blog, filename: string): void {
        const path = j(this.getDir(blog), filename)
        if (existsSync(path))
            unlinkSync(path)

        // Remove thumbnails of images
        if ((getType(path) || '').includes('image')) {
            for (const height of IMAGE_SIZES) {
                const thumbPath = path.replace('.webp', 'h' + height + '.webp')
                if (existsSync(thumbPath))
                    unlinkSync(thumbPath)
            }
        }
    }
开发者ID:m1cr0man,项目名称:m1cr0blog,代码行数:14,代码来源:repository.ts

示例6: outgoingHandler

  async function outgoingHandler(event: sdk.IO.Event, next: sdk.IO.MiddlewareNextCallback) {
    if (event.channel !== 'web') {
      return next()
    }

    const messageType = event.type === 'default' ? 'text' : event.type
    const userId = event.target
    const conversationId = event.threadId || (await db.getOrCreateRecentConversation(event.botId, userId))

    if (!_.includes(outgoingTypes, messageType)) {
      return next(new Error('Unsupported event type: ' + event.type))
    }

    if (messageType === 'typing') {
      const typing = parseTyping(event.payload.value)
      const payload = bp.RealTimePayload.forVisitor(userId, 'webchat.typing', { timeInMs: typing, conversationId })
      // Don't store "typing" in DB
      bp.realtime.sendPayload(payload)
      await Promise.delay(typing)
    } else if (messageType === 'text' || messageType === 'carousel') {
      const message = await db.appendBotMessage(botName, botAvatarUrl, conversationId, {
        data: event.payload,
        raw: event.payload,
        text: event.preview,
        type: messageType
      })

      bp.realtime.sendPayload(bp.RealTimePayload.forVisitor(userId, 'webchat.message', message))
    } else if (messageType === 'file') {
      const extension = path.extname(event.payload.url)
      const mimeType = mime.getType(extension)
      const basename = path.basename(event.payload.url, extension)

      const message = await db.appendBotMessage(botName, botAvatarUrl, conversationId, {
        data: { storage: 'storage', mime: mimeType, name: basename, ...event.payload },
        raw: event.payload,
        text: event.preview,
        type: messageType
      })

      bp.realtime.sendPayload(bp.RealTimePayload.forVisitor(userId, 'webchat.message', message))
    } else {
      throw new Error(`Message type "${messageType}" not implemented yet`)
    }

    next(undefined, false)
    // TODO Make official API (BotpressAPI.events.updateStatus(event.id, 'done'))
  }
开发者ID:seffalabdelaziz,项目名称:botpress,代码行数:48,代码来源:socket.ts

示例7: filePathToLocalFileResponseParam

 protected async filePathToLocalFileResponseParam(
     filePath: AutoResponderFilePath,
 ): Promise<LocalFileResponseParam | null> {
     let stats;
     try {
         stats = await filePath.getState();
     } catch (e) {
         // missing file
         return null;
     }
     return {
         path: filePath.value,
         type: mime.getType(filePath.value),
         size: stats.size,
     };
 }
开发者ID:kyo-ago,项目名称:lifter,代码行数:16,代码来源:auto-responder-entity.ts

示例8: upload

  // http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html
  async upload(task: UploadTask): Promise<any> {
    const fileName = path.basename(task.file)
    const cancellationToken = this.context.cancellationToken

    const target = (this.options.path == null ? "" : `${this.options.path}/`) + fileName

    if (process.env.__TEST_S3_PUBLISHER__ != null) {
      const testFile = path.join(process.env.__TEST_S3_PUBLISHER__!, target)
      await ensureDir(path.dirname(testFile))
      await symlink(task.file, testFile)
      return
    }

    const s3Options: CreateMultipartUploadRequest  = {
      Key: target,
      Bucket: this.getBucketName(),
      ContentType: mime.getType(task.file) || "application/octet-stream"
    }
    this.configureS3Options(s3Options)

    const contentLength = task.fileContent == null ? (await stat(task.file)).size : task.fileContent.length
    const uploader = new Uploader(new S3(this.createClientConfiguration()), s3Options, task.file, contentLength, task.fileContent)

    const progressBar = this.createProgressBar(fileName, uploader.contentLength)
    if (progressBar != null) {
      const callback = new ProgressCallback(progressBar)
      uploader.on("progress", () => {
        if (!cancellationToken.cancelled) {
          callback.update(uploader.loaded, uploader.contentLength)
        }
      })
    }

    return await cancellationToken.createPromise((resolve, reject, onCancel) => {
      onCancel(() => uploader.abort())
      uploader.upload()
        .then(() => {
          try {
            log.debug({provider: this.providerName, file: fileName, bucket: this.getBucketName()}, "uploaded")
          }
          finally {
            resolve()
          }
        })
        .catch(reject)
    })
  }
开发者ID:ledinhphuong,项目名称:electron-builder,代码行数:48,代码来源:BaseS3Publisher.ts

示例9: upload

  // http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/s3-example-creating-buckets.html
  async upload(file: string, arch: Arch, safeArtifactName?: string): Promise<any> {
    const fileName = path.basename(file)
    const fileStat = await stat(file)
    const cancellationToken = this.context.cancellationToken

    const target = (this.options.path == null ? "" : `${this.options.path}/`) + fileName

    if (process.env.__TEST_S3_PUBLISHER__ != null) {
      const testFile = path.join(process.env.__TEST_S3_PUBLISHER__!, target)
      await ensureDir(path.dirname(testFile))
      await symlink(file, testFile)
      return
    }

    const s3Options: CreateMultipartUploadRequest  = {
      Key: target,
      Bucket: this.getBucketName(),
      ContentType: mime.getType(file) || "application/octet-stream"
    }
    this.configureS3Options(s3Options)

    const uploader = new Uploader(new S3(this.createClientConfiguration()), s3Options, file, fileStat)

    const progressBar = this.createProgressBar(fileName, fileStat)
    if (progressBar != null) {
      const callback = new ProgressCallback(progressBar)
      uploader.on("progress", () => {
        if (!cancellationToken.cancelled) {
          callback.update(uploader.loaded, uploader.contentLength)
        }
      })
    }

    return cancellationToken.createPromise((resolve, reject, onCancel) => {
      onCancel(() => uploader.abort())
      uploader.upload()
        .then(() => {
          try {
            debug(`${this.providerName} Publisher: ${fileName} was uploaded to ${this.getBucketName()}`)
          }
          finally {
            resolve()
          }
        })
        .catch(reject)
    })
  }
开发者ID:jwheare,项目名称:electron-builder,代码行数:48,代码来源:basePublisher.ts

示例10: defaultFileServerSettings

export function defaultFileServerSettings(dir: string): StaticSettings {
  return {
    lookupFile(pieces: Piece[]) {
      return fileSystemLookup(defaultEtag, dir, pieces, false);
    },
    getMimeType(file: File) {
      return T.pure(getType(file.name) || 'application/octet-stream');
    },
    indices: ['index.html', 'index.htm'],
    listing: just(defaultListing),
    maxAge: { tag: MaxAgeType.NoMaxAge },
    mkRedirect: defaultMkRedirect,
    redirectToIndex: false,
    useHash: false,
    weakEtags: false,
    addTrailingSlash: false,
    notFoundHandler: nothing
  };
}
开发者ID:syaiful6,项目名称:jonggrang,代码行数:19,代码来源:fs.ts

示例11: defaultWebAppSettings

export function defaultWebAppSettings(dir: string, weakEtag?: boolean): StaticSettings {
  const weakEtags = weakEtag === undefined ? true : weakEtag;
  return {
    lookupFile(pieces: Piece[]) {
      return webAppLookup(defaultEtag, dir, pieces, this.weakEtags);
    },
    getMimeType(file: File) {
      return T.pure(getType(file.name) || 'application/octet-stream');
    },
    indices: [],
    listing: nothing,
    maxAge: { tag: MaxAgeType.MaxAgeForever },
    mkRedirect: defaultMkRedirect,
    redirectToIndex: false,
    useHash: true,
    weakEtags: weakEtags,
    addTrailingSlash: false,
    notFoundHandler: nothing
  };
}
开发者ID:syaiful6,项目名称:jonggrang,代码行数:20,代码来源:fs.ts

示例12: next

app.use((ctx, next) => {
    if (ctx.method !== 'GET' && ctx.method !== 'HEAD') {
        ctx.status = 405;
        ctx.length = 0;
        ctx.set('Allow', 'GET, HEAD');
        next();
        return (false);
    }

    const filePath = ctx.path[ctx.path.length - 1] === '/'
        ? join(output, ctx.path, 'index.html')
        : join(output, ctx.path);

    if (!fileSystem.existsSync(filePath)) {
        ctx.status = 404;
        ctx.length = 0;
        next();
        return (false);
    }

    const fileStat = fileSystem.statSync(filePath);

    ctx.type = getType(filePath)!;
    ctx.lastModified = new Date();

    ctx.set('Accept-Ranges', 'bytes');
    ctx.set('Cache-Control', 'max-age=0');

    // node-fs
    if (fileStat instanceof fs.Stats) {
        ctx.length = fileStat.size;
    }
    // memory-fs
    else {
        ctx.length = Buffer.from(fileSystem.readFileSync(filePath)).length;
    }

    ctx.body = fileSystem.createReadStream(filePath);
    next();
});
开发者ID:rectification,项目名称:circuitlab,代码行数:40,代码来源:webpack.dev.ts

示例13: constructor

    constructor(props: {
        url: string,
        data: Buffer | string,
        ns?: string,
        mimeType?: string,
        title?: string,
        redirectAid?: string,
        aid?: string,
        fileName?: string,
        shouldIndex?: boolean
    }, ...args: any[]) {
        if (args.length) {
            // CPP hack
            const url = props
            props = { url } as any
            const keys = ['data', 'ns', 'mimeType', 'title', 'redirectAid', 'aid', 'fileName', 'shouldIndex']
            for (let i in args) {
                (props as any)[keys[i]] = args[i]
            }
        }
        props.ns = props.ns || '.'
        props.title = props.title || ''
        props.fileName = props.fileName || ''
        props.shouldIndex = props.shouldIndex || false
        props.redirectAid = props.redirectAid || ''
        props.aid = props.aid || `${props.ns}/${props.url}`

        if (!props.mimeType) props.mimeType = mime.getType(props.url) || 'text/plain';

        this.ns = props.ns;
        this.aid = props.aid;
        this.url = props.url;
        this.title = props.title;
        this.mimeType = props.mimeType;
        this.redirectAid = props.redirectAid;
        this.fileName = props.fileName;
        this.shouldIndex = props.shouldIndex;
        this.bufferData = props.data && Buffer.from(props.data as any);
    }
开发者ID:kiwix,项目名称:node-libzim,代码行数:39,代码来源:Article.ts

示例14: stat

export function stat(req: Http2ServerRequest, res: Http2ServerResponse, roots: Array<string>): void {
    const copyRoots = roots.slice();
    const [url] = req.url.split('?');
    const contentType = getType(url);

    const check = (root: string) => {
        const path = join(root, url);
        readFile(path).then((file: Buffer) => {
            res.setHeader('Cache-Control', 'public, max-age=31557600');
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(file);
        })
            .catch(() => {
                if (copyRoots.length) {
                    check(copyRoots.pop());
                } else {
                    res.writeHead(404, { 'Content-Type': 'text/plain' });
                    res.end('404 Not Found\n');
                }
            });
    };

    check(copyRoots.pop());
}
开发者ID:wavesplatform,项目名称:WavesGUI,代码行数:24,代码来源:utils.ts

示例15: Mime

import * as mime from "mime";
import Mime from "mime/Mime";

let strOrNul: string | null;

const obj = {
	mime: ["ext", "ext2"]
};

const obj2 = {
	"text/plain": ["txt"]
};

mime.define(obj);
mime.define(obj2, true);
strOrNul = mime.getType("ext");
strOrNul = mime.getType("foo");
strOrNul = mime.getExtension("mime");
strOrNul = mime.getExtension("bar");

const myMime = new Mime(obj);
strOrNul = myMime.getType("foo");
strOrNul = myMime.getExtension('text/plan');
开发者ID:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:23,代码来源:mime-tests.ts


注:本文中的mime.getType函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。