我正在将Firebase与我的React项目一起使用,并在用户上传图片时尝试调整其大小。我正在使用的云功能可以正常工作,但是执行它需要花费8到10秒钟以上的时间,我觉得它不应该花那么长时间。我正在使用sharp
库调整图像大小,并使用Firebase的“ Spark”(免费)计划。关于如何提高性能的任何想法?这是我的云函数:
const functions = require('firebase-functions');
const {Storage} = require('@google-cloud/storage');
const sharp = require('sharp');
const os = require('os');
const path = require('path');
const projectId = 'my-project-id';
const storage = new Storage({
projectId: projectId
});
exports.resizeImage = functions.storage.object('images').onFinalize(event => {
const {bucket, name, contentType, resourceState} = event;
if (!contentType.startsWith('image/') || resourceState == 'not_exists') {
console.log('This is not an image.');
return {};
}
if (path.basename(name).startsWith('resized_')){
console.log('Image already processed');
return {};
}
const destinationBucket = storage.bucket(bucket);
const workingDir = path.join(os.tmpdir());
const tempFilePath = path.join(workingDir, path.basename(name));
const metadata = {contentType: contentType};
return destinationBucket.file(name).download({
destination: tempFilePath
})
.then(() => {
const newFilePath = path.join(workingDir, 'resized_' + path.basename(name));
sharp(tempFilePath)
.resize({width: 600})
.toFile(newFilePath)
.then( () => {
return destinationBucket.upload(newFilePath, {destination: 'images/resized_' + path.basename(name)});
})
.catch( err => console.log(err))
})
})