在node.js上使用sharp库我们如何在链接条件中添加条件我尝试使用它。那可能吗?
S3.getObject({Bucket: BUCKET, Key: originalKey}).promise()
.then(data => Sharp(data.Body)
if(useCrop){
.crop(width, height)
}
if(useResize){
.resize(width, height)
}
.toFormat(setFormat)
.withoutEnlargement(p_withoutEnlargement)
.quality(quality)
.max(max)
.flatten()
.toBuffer()
)
.then(buffer => S3.putObject({
Body: buffer,
Bucket: BUCKET,
ContentType: 'image/'+setFormat,
CacheControl: `max-age=${maxAge}`,
Key: key,
}).promise()
)
.then(() => callback(null, {
statusCode: '301',
headers: {'location': `${URL}/${key}`},
body: '',
})
)
只需使用临时变量:
.then(data => {
let s = Sharp(data.Body);
if(useCrop){
s = s.crop(width, height)
}
if(useResize){
s = s.resize(width, height)
}
return s.toFormat(setFormat)
.withoutEnlargement(p_withoutEnlargement)
.quality(quality)
.max(max)
.flatten()
.toBuffer();
})
你也可以不做突变:
const orig = Sharp(data.Body);
const withPossibleCrop = useCrop ? orig.crop(width, height) : orig;
const withPossibleCropAndResize = useResize ? withPossibleCrop.resize(width, height) : withPossibleCrop;
return withPossibleCropAndResize.toFormat(…).…;