andrewrk / node-s3-client

high level amazon s3 client for node.js
MIT License
1k stars 305 forks source link

Is there a way to check if a file already exists in s3 bucket? #88

Closed raeesaa closed 8 years ago

raeesaa commented 9 years ago

Hi,

First of all thank you for a great library. I have been using it for uploading images to s3 since past 2 months and did not face any issues so far.

There is a new requirement in my application now where I am required to check if a file already exists in the s3 bucket. Is it possible to do that using this library? I went through the readme but did not find any function that would help me in doing that.

Thanks, Raeesaa

sq-ricardo-pereira commented 9 years ago

Hi, you can use aws-sdk of the amazon.

var s3 = new AWS.S3();
var params = {Bucket: 'mybucket', Key: 'myfile'};
s3.getObject(params).on('success', function(response) {
  console.log("Key was", response.request.params.Key);
}).on('error',function(error){
     //error return a object with status code 404
}).send();

To more information, look this: http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-making-requests.html

gswalden commented 8 years ago

Extending @qixmiers's answer, it's generally faster to use a HEAD request:

var s3 = new AWS.S3();
var params = {Bucket: 'mybucket', Key: 'myfile'};
s3.headObject(params).on('success', function(response) {
  console.log("Key was", response.request.params.Key);
}).on('error',function(error){
     //error return a object with status code 404
}).send();
faceleg commented 8 years ago

Excellent advice!

I'd be more than willing to merge in a PR that added a "examples" section to the readme that offered advice like this @gswalden @qixmiers

dkebler commented 8 years ago

so per the readme given
var s3 = require('s3'); s3.AWS is supposed to access the AWS SDK API which it does for example with s3.AWS.config.region = 'us-west-2'

but short of having to make a separate AWS.S3 object (like the example above) can we access the AWS-SDK S3 methods like for example headBucket and headObject from your s3 object?

_these don't work__

s3.AWS.headBucket(params, function(err, data) { ....}
s3.AWS.S3.headBucket(params, function(err, data) { ....}

Happy to do PR to the readme (this and setting region and more) if I can understand your API better.