How to determine if object exists AWS S3 Node.JS sdk

后端 未结 8 1551
梦毁少年i
梦毁少年i 2020-12-13 03:39

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


        
相关标签:
8条回答
  • 2020-12-13 04:08

    Use getObject method like this:

    var params = {
        Bucket: config.get('s3bucket'),
        Key: path
    };
    s3.getObject(params, function(err, data){
        if(err) {
            console.log(err);
        }else {
          var signedURL = s3.getSignedUrl('getObject', params, callback);
          console.log(signedURL);
       }
    });
    
    0 讨论(0)
  • 2020-12-13 04:10

    by using headObject method

    AWS.config.update({
            accessKeyId: "*****",
            secretAccessKey: "****",
            region: region,
            version: "****"
        });
    const s3 = new AWS.S3();
    
    const params = {
            Bucket: s3BucketName,
            Key: "filename" //if any sub folder-> path/of/the/folder.ext
    }
    try {
            await s3.headObject(params).promise()
            console.log("File Found in S3")
        } catch (err) {
            console.log("File not Found ERROR : " + err.code)
    }
    

    As params are constant, the best way to use it with const. If the file is not found in the s3 it throws the error NotFound : null.

    If you want to apply any operations in the bucket, you have to change the permissions of CORS Configuration in the respective bucket in the AWS. For changing permissions Bucket->permission->CORS Configuration and Add this code.

    <CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
    </CORSConfiguration>
    

    for more information about CORS Configuration : https://docs.aws.amazon.com/AmazonS3/latest/dev/cors.html

    0 讨论(0)
提交回复
热议问题