在node.js链接中使用if条件

问题描述 投票:0回答:1

在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: '',
    })
)
javascript node.js node-modules
1个回答
2
投票

只需使用临时变量:

.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(…).…;
© www.soinside.com 2019 - 2024. All rights reserved.