I am having a S3 bucket with folders and sub-folders containing files, I am trying to list all the folder names inside root directory. I dont want to list the sub-folders and files.
ex:
Test/Test1
Test/Test2
Test/Test3
Test/Test4
etc...
I have tried the following code which lists all the keys inside root directory
getListAllKeys(rootDirectory) {
const containedEntities = {
files: [],
directories: []
};
const params = {
Bucket: this.bucket,
Prefix: Test/,
Delimiter: Test/
};
return new Promise((resolve, reject) => this._listAllKeys(
resolve,
reject,
params,
containedEntities
));
}
_listAllKeys(resolve, reject, params, containedEntities) {
this.s3.listObjectsV2(params).promise()
.then(({
Contents, IsTruncated, NextContinuationToken,
}) => {
// filter files and directories
Contents.forEach((item) => {
containedEntities[item.Key.endsWith('/') ? 'directories' : 'files'].push(item);
});
// fetch further info if response is truncated
if (IsTruncated) {
this._listAllKeys(
resolve,
reject,
Object.assign(params, { ContinuationToken: NextContinuationToken }),
containedEntities
);
} else {
resolve(containedEntities);
}
})
.catch(reject);
}
I am using AWS-SDK package. Please let me know how to list only the main folders
CodePudding user response:
To obtain a list of directories, specify Delimiter='/'
(with no Prefix specified).
A list of directories at the top (root) level will be returned in a list called CommonPrefixes
.
It also works for sub-folders by specifying a Prefix.