UNPKG

@rytass/file-converter-adapter-image-transcoder

Version:

Rytass Utils Storages Images Converter

52 lines (46 loc) 1.24 kB
'use strict'; var sharp = require('sharp'); var stream = require('stream'); var fileType = require('file-type'); const SupportSources = [ 'jpg', 'png', 'webp', 'gif', 'avif', 'tif', 'svg' ]; class UnsupportedSource extends Error { message = 'UnsupportedSource'; } sharp.cache(false); class ImageTranscoder { options; constructor(options){ this.options = options; sharp.concurrency(options.concurrency ?? 1); } async convert(file) { let converter; if (file instanceof Buffer) { const extension = await fileType.fromBuffer(file); if (!extension || !~SupportSources.indexOf(extension.ext)) { throw new UnsupportedSource(); } converter = sharp(file); } else { converter = sharp(); } converter.toFormat(this.options.targetFormat, this.options); // Stream cannot throw when format not supported if (file instanceof stream.Readable) { file.pipe(converter); } if (file instanceof Buffer) { return converter.toBuffer(); } return converter; } } exports.ImageTranscoder = ImageTranscoder;