Node.js & Amazon S3: How to iterate through all files in a bucket?

前端 未结 15 1014
情书的邮戳
情书的邮戳 2020-12-02 14:17

Is there any Amazon S3 client library for Node.js that allows listing of all files in S3 bucket?

The most known aws2js and knox don\'t seem to have this functionalit

15条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 14:43

    I ended up building a wrapper function around ListObjectsV2, works the same way and takes the same parameters but works recursively until IsTruncated=false and returns all the keys found as an array in the second parameter of the callback function

    const AWS = require('aws-sdk')
    const s3 = new AWS.S3()
    
    function listAllKeys(params, cb)
    {
       var keys = []
       if(params.data){
          keys = keys.concat(params.data)
       }
       delete params['data']
    
       s3.listObjectsV2(params, function(err, data){
         if(err){
           cb(err)
         } else if (data.IsTruncated) {
           params['ContinuationToken'] = data.NextContinuationToken
           params['data'] = data.Contents
           listAllKeys(params, cb)
         } else {
           keys = keys.concat(data.Contents)
           cb(null,keys)
         }
       })
    }
    

提交回复
热议问题