• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript file-type.default函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: Error

export async function encode(key: string) {
  const { Body: body } = await s3.getObject({
    Bucket: S3_BUCKET_BEFORE_ENCODE,
    Key: key,
  }).promise();

  const { ext, mime } = fileType(body);

  if (['image', 'video'].every((type) => !mime.startsWith(type))) {
    throw new Error(`Cannot encode media ${mime}`);
  }

  const encodedMedia = mime.startsWith('image/') && ext !== 'gif'
    ? await encodeImage(body)
    : await encodeVideo(body);
  console.log('after encode');
  const encodedMediaMime = fileType(encodedMedia).mime;

  await s3.putObject({
    Bucket: S3_BUCKET_AFTER_ENCODE,
    Key: key,
    Body: encodedMedia,
    ContentType: encodedMediaMime,
  }).promise();
}
开发者ID:skatpgusskat,项目名称:redchat,代码行数:25,代码来源:encode.ts


示例2: detectFileType

export function detectFileType(data: string | Buffer, fileName?: string) {
    const dataSample = getUint8Array(data);

    if (isDlog(dataSample)) {
        return {
            ext: "dlog",
            mime: MIME_EEZ_DLOG
        };
    }

    let type = fileType(dataSample, "binary");

    if (type) {
        return type;
    }

    if (isSimpleCSV(data)) {
        return {
            ext: "csv",
            mime: "text/csv"
        };
    }

    let ext: string | undefined = undefined;
    if (fileName) {
        ext = getFileNameExtension(fileName);
        if (ext) {
            if (ext.toLowerCase() === "raw") {
                return {
                    ext,
                    mime: "application/eez-raw"
                };
            }
        }
    }

    return {
        ext,
        mime: "application/octet-stream"
    };
}
开发者ID:eez-open,项目名称:studio,代码行数:41,代码来源:file-type.ts


示例3: fileRoute

export function fileRoute(server: CodeServerRouter, options: ServerOptions) {
  async function repoExists(req: hapi.Request, repoUri: string) {
    const repoObjectClient = new RepositoryObjectClient(new EsClientWithRequest(req));

    try {
      // Check if the repository already exists
      await repoObjectClient.getRepository(repoUri);
      return true;
    } catch (e) {
      return false;
    }
  }

  server.route({
    path: '/api/code/repo/{uri*3}/tree/{ref}/{path*}',
    method: 'GET',
    async handler(req: hapi.Request) {
      const fileResolver = new GitOperations(options.repoPath);
      const { uri, path, ref } = req.params;
      const queries = req.query as RequestQuery;
      const limit = queries.limit
        ? parseInt(queries.limit as string, 10)
        : DEFAULT_TREE_CHILDREN_LIMIT;
      const skip = queries.skip ? parseInt(queries.skip as string, 10) : 0;
      const depth = queries.depth ? parseInt(queries.depth as string, 10) : 0;
      const withParents = 'parents' in queries;
      const flatten = 'flatten' in queries;
      const repoExist = await repoExists(req, uri);
      if (!repoExist) {
        return Boom.notFound(`repo ${uri} not found`);
      }

      try {
        return await fileResolver.fileTree(
          uri,
          path,
          ref,
          skip,
          limit,
          withParents,
          depth,
          flatten
        );
      } catch (e) {
        if (e.isBoom) {
          return e;
        } else {
          return Boom.internal(e.message || e.name);
        }
      }
    },
  });

  server.route({
    path: '/api/code/repo/{uri*3}/blob/{ref}/{path*}',
    method: 'GET',
    async handler(req: hapi.Request, h: hapi.ResponseToolkit) {
      const fileResolver = new GitOperations(options.repoPath);
      const { uri, path, ref } = req.params;
      const repoExist = await repoExists(req, uri);
      if (!repoExist) {
        return Boom.notFound(`repo ${uri} not found`);
      }
      try {
        const blob = await fileResolver.fileContent(uri, path, decodeURIComponent(ref));
        if (blob.isBinary()) {
          const type = fileType(blob.content());
          if (type && type.mime && type.mime.startsWith('image/')) {
            const response = h.response(blob.content());
            response.type(type.mime);
            return response;
          } else {
            // this api will return a empty response with http code 204
            return h
              .response('')
              .type('application/octet-stream')
              .code(204);
          }
        } else {
          const line = (req.query as RequestQuery).line as string;
          if (line) {
            const [from, to] = line.split(',');
            let fromLine = parseInt(from, 10);
            let toLine = to === undefined ? fromLine + 1 : parseInt(to, 10);
            if (fromLine > toLine) {
              [fromLine, toLine] = [toLine, fromLine];
            }
            const lines = extractLines(blob.content(), fromLine, toLine);
            const lang = await detectLanguage(path, lines);
            return h.response(lines).type(`text/${lang || 'plain'}`);
          } else if (blob.content().length <= TEXT_FILE_LIMIT) {
            const lang = await detectLanguage(path, blob.content());
            return h.response(blob.content()).type(`text/${lang || 'plain'}`);
          } else {
            return h.response('').type(`text/big`);
          }
        }
      } catch (e) {
        if (e.isBoom) {
          return e;
//.........这里部分代码省略.........
开发者ID:elastic,项目名称:kibana,代码行数:101,代码来源:file.ts


示例4: Pageres

test('`format` option', async t => {
	const screenshots = await new Pageres().src(server.url, ['100x100'], {format: 'jpg'}).run();
	t.is(fileType(screenshots[0]).mime, 'image/jpeg');
});
开发者ID:sindresorhus,项目名称:pageres,代码行数:4,代码来源:test.ts


示例5: reject

) => new Promise<any>(async (resolve, reject) => {
	// File size
	const size = data.byteLength;

	// File type
	let mime = 'application/octet-stream';
	const type = fileType(data);
	if (type !== null) {
		mime = type.mime;

		if (name === null) {
			name = `untitled.${type.ext}`;
		}
	} else {
		if (name === null) {
			name = 'untitled';
		}
	}

	// Generate hash
	const hash = crypto
		.createHash('sha256')
		.update(data)
		.digest('hex') as string;

	if (!force) {
		// Check if there is a file with the same hash and same data size (to be safe)
		const much = await DriveFile.findOne({
			user_id: user._id,
			hash: hash,
			datasize: size
		});

		if (much !== null) {
			resolve(much);
			return;
		}
	}

	// Fetch all files to calculate drive usage
	const files = await DriveFile
		.find({ user_id: user._id }, {
			datasize: true,
			_id: false
		})
		.toArray();

	// Calculate drive usage (in byte)
	const usage = files.map(file => file.datasize).reduce((x, y) => x + y, 0);

	// If usage limit exceeded
	if (usage + size > user.drive_capacity) {
		return reject('no-free-space');
	}

	// If the folder is specified
	let folder: any = null;
	if (folderId !== null) {
		folder = await DriveFolder
			.findOne({
				_id: folderId,
				user_id: user._id
			});

		if (folder === null) {
			return reject('folder-not-found');
		}
	}

	let properties: any = null;

	// If the file is an image
	if (/^image\/.*$/.test(mime)) {
		// Calculate width and height to save in property
		const g = gm(data, name);
		const size = await prominence(g).size();
		properties = {
			width: size.width,
			height: size.height
		};
	}

	// Create DriveFile document
	const res = await DriveFile.insert({
		created_at: new Date(),
		user_id: user._id,
		folder_id: folder !== null ? folder._id : null,
		data: data,
		datasize: size,
		type: mime,
		name: name,
		comment: comment,
		hash: hash,
		properties: properties
	});

	const file = res.ops[0];

	resolve(file);

//.........这里部分代码省略.........
开发者ID:syuilo,项目名称:misskey-core,代码行数:101,代码来源:add-file-to-drive.ts



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript file-url.default函数代码示例发布时间:2022-05-25
下一篇:
TypeScript file-system.path类代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap