0

i m trying to get list of folders with using a package aws-sdk and the method listObjects

but i am getting files in these folders, i want to leave them and take only folders, for example:

const AWS = require('aws-sdk');
const { Contents: files } = await new AWS.S3()
     .listObjects({
        Bucket : 'myBucketName',
        Prefix : `configs/config2`
     })
     .promise();

the response (i've simplified it) is:

[ { Key: 'configs/config2/0.0.0/index.js'},
  { Key: 'configs/config2/0.0.1/index.js'},
  { Key: 'configs/config2/0.1.0/index.js'},
  { Key: 'configs/config2/0.2.0/index.js'} ]

my aim is to get only folders, i do not want to get scripts

[ { Key: 'configs/config2/0.0.0'},
  { Key: 'configs/config2/0.0.1'},
  { Key: 'configs/config2/0.1.0'},
  { Key: 'configs/config2/0.2.0'} ]
Max
  • 781
  • 7
  • 19
  • Possible duplicate of [Amazon S3: How to get a list of folders in the bucket?](https://stackoverflow.com/questions/33545065/amazon-s3-how-to-get-a-list-of-folders-in-the-bucket) – ponury-kostek Aug 01 '19 at 14:44
  • can you provide it in js ? – Max Aug 01 '19 at 14:45
  • I think [this](https://stackoverflow.com/a/14653973/8905352) answer will solve your issue – Miguel Aug 01 '19 at 14:48

1 Answers1

0

Well, its a simple manner of string manipulations. you use a combination of string.lastIndexOf to find the last occourence of '/' char:

The lastIndexOf() method returns the position of the last occurrence of a specified value in a string. use string.lastIndexOf to find the last occurence of / .

Note: The string is searched from the end to the beginning, but returns the index starting at the beginning, at position 0.

This method returns -1 if the value to search for never occurs.

Note: The lastIndexOf() method is case sensitive!

And then combine it with string.slice to get rid of the rest:

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.

And you get something like:

folderPath = filePath.slice(0, filePath.lastIndexOf('/')).

if you got an array of string, jsut throw that as the return for the .map method.

AFAIK, you cannot send a request to list just folders because the "folder" is actualyl just visualization manner. The bucket actually stores all object toghther and if their name contains '/' in it it will display them as if they were under a folder.

Community
  • 1
  • 1
Gibor
  • 1,695
  • 6
  • 20