Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

amazon web services - How to determine if object exists AWS S3 Node.JS 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);

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".

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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  
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...