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

后端 未结 8 1550
梦毁少年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 03:48

    Synchronous call on S3 in Nodejs instead of asynchronous call using Promise

    var request = require("request");
    var AWS = require("aws-sdk");
    
    AWS.config.update({
        accessKeyId: "*****",
        secretAccessKey: "********"
    });
    
    
    const s3 = new AWS.S3();
    
    
    var response;
    
    function initialize(bucket,key) {
        // Setting URL and headers for request
        const params = {
            Bucket: bucket,
            Key: key
        };
        // Return new promise 
        return new Promise(function(resolve, reject) {
            s3.headObject(params, function(err, resp, body) {  
                if (err) {  
                    console.log('Not Found : ' + params.Key );
                    reject(params.Key);
                } else {  
                    console.log('Found : ' + params.Key );
                    resolve(params.Key);
                }
              })
        })
    }
    
    function main() {
    
        var foundArray = new Array();
        var notFoundArray = new Array();
        for(var i=0;i<10;i++)
        {
            var key = '1234'+ i;
            var initializePromise = initialize('****',key);
            initializePromise.then(function(result) {
                console.log('Passed for : ' + result);
                foundArray.push(result);
                console.log (" Found Array : "+ foundArray);
            }, function(err) {
                console.log('Failed for : ' + err);
                notFoundArray.push(err);
                console.log (" Not Found Array : "+ notFoundArray);
            });
        }
    
    
    }
    
    main();
    
    0 讨论(0)
  • 2020-12-13 03:53

    You can also use the waitFor method together with the state objectExists. This will use S3.headObject() internally.

    var params = {
      Bucket: config.get('s3bucket'),
      Key: path
    };
    s3.waitFor('objectExists', params, function(err, data) {
      if (err) console.log(err, err.stack); // an error occurred
      else     console.log(data);           // successful response
    });
    
    0 讨论(0)
  • 2020-12-13 03:54

    The simplest solution without try/catch block.

    const exists = await s3
      .headObject({
        Bucket: S3_BUCKET_NAME,
        Key: s3Key,
      })
      .promise()
      .then(
        () => true,
        err => {
          if (err.code === 'NotFound') {
            return false;
          }
          throw err;
        }
      );
    
    0 讨论(0)
  • 2020-12-13 03:55

    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  
      }
    }
    
    0 讨论(0)
  • 2020-12-13 03:59

    Promise.All without failure Synchronous Operation

    var request = require("request");
    var AWS = require("aws-sdk");
    
    AWS.config.update({
        accessKeyId: "*******",
        secretAccessKey: "***********"
    });
    
    
    const s3 = new AWS.S3();
    
    
    var response;
    
    function initialize(bucket,key) {
        // Setting URL and headers for request
        const params = {
            Bucket: bucket,
            Key: key
        };
        // Return new promise 
        return new Promise(function(resolve, reject) {
            s3.headObject(params, function(err, resp, body) {  
                if (err) {  
                    resolve(key+"/notfound");
                } else{
                    resolve(key+"/found");
                }
              })
        })
    }
    
    function main() {
    
        var foundArray = new Array();
        var notFoundArray = new Array();
        var prefix = 'abc/test/';
        var promiseArray = [];
        try{
        for(var i=0;i<10;i++)
        {
            var key = prefix +'1234' + i;
            console.log("Key : "+ key);
            promiseArray[i] = initialize('bucket',key);
            promiseArray[i].then(function(result) {
                console.log("Result : " + result);
                var temp = result.split("/");
                console.log("Temp :"+ temp);
                if (temp[3] === "notfound")
                {
                    console.log("NOT FOUND");
                }else{
                    console.log("FOUND");
                }
    
            }, function(err) {
                console.log (" Error ");
            });
        }
    
        Promise.all(promiseArray).then(function(values) {
            console.log("^^^^^^^^^^^^TESTING****");
          }).catch(function(error) {
              console.error(" Errro : "+ error);
          });
    
    
    
    
    }catch(err){
        console.log(err);
    }
    
    
    }
    
    main();
    
    0 讨论(0)
  • 2020-12-13 04:01

    Synchronous Put Operation

    var request = require("request");
    var AWS = require("aws-sdk");
    
    AWS.config.update({
        accessKeyId: "*****",
        secretAccessKey: "***"
    });
    
    
    const s3 = new AWS.S3();
    
    
    var response;
    
    function initialize(bucket,key) {
        // Setting URL and headers for request
        const params = {
            Bucket: bucket,
            Key: key
        };
        // Return new promise 
        return new Promise(function(resolve, reject) {
            s3.putObject(params, function(err, resp, body) {  
                if (err) {  
                    reject();
                } else {  
                    resolve();
                }
              })
        })
    }
    
    function main() {
    
        var promiseArray = [];
        var prefix = 'abc/test/';
        for(var i=0;i<10;i++)
        {
            var key = prefix +'1234'+ i;
            promiseArray[i] = initialize('bucket',key);
            promiseArray[i].then(function(result) {
                console.log (" Successful ");
            }, function(err) {
                console.log (" Error ");
            });
        }
    
    
          console.log('Promises ' + promiseArray);
    
    
        Promise.all(promiseArray).then(function(values) {
            console.log("******TESTING****");
          });
    
    
    }
    
    
    main();
    
    0 讨论(0)
提交回复
热议问题