如何确定对象是否存在 AWS S3 Node.JS sdk [英] How to determine if object exists AWS S3 Node.JS sdk

查看:23
本文介绍了如何确定对象是否存在 AWS S3 Node.JS sdk的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 AWS SDK 检查文件是否存在.这是我正在做的:

I need to check if a file exists using AWS SDK. Here is what I'm doing:

var params = {
    Bucket: config.get('s3bucket'),
    Key: path
};

s3.getSignedUrl('getObject', params, callback);

它有效,但问题是当对象不存在时,回调(带有参数 err 和 url)不返回错误,当我尝试访问 URL 时,它显示NoSuchObject".

It works but the problem is that when the object doesn't exists, the callback (with arguments err and url) returns no error, and when I try to access the URL, it says "NoSuchObject".

当对象不存在时,这个 getSignedUrl 方法不应该返回一个错误对象吗?如何判断对象是否存在?我真的需要调用返回的 URL 吗?

Shouldn't this getSignedUrl method return an error object when the object doesn't exists? How do I determine if the object exists? Do I really need to make a call on the returned URL?

推荐答案

在创建签名 URL 之前,您需要检查该文件是否直接从存储桶中存在.一种方法是请求 HEAD 元数据.

Before creating the signed URL, you need to check if the file exists directly from the bucket. One way to do that is by requesting the HEAD metadata.

// Using callbacks
s3.headObject(params, function (err, metadata) {  
  if (err && err.code === 'NotFound') {  
    // Handle no object on cloud here  
  } else {  
    s3.getSignedUrl('getObject', params, callback);  
  }
});

// Using async/await (untested)
try { 
  const headCode = await s3.headObject(params).promise();
  const signedUrl = s3.getSignedUrl('getObject', params);
  // Do something with signedUrl
} catch (headErr) {
  if (headErr.code === 'NotFound') {
    // Handle no object on cloud here  
  }
}

这篇关于如何确定对象是否存在 AWS S3 Node.JS sdk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆