I am using aws-sdk using node.js. I want to list images in specified folder e.g.
I put up a little module which lists contents of a "folder" you give it:
s3ls({bucket: 'my-bucket-name'}).ls('/', console.log);
will print something like this:
{ files: [ 'funny-cat-gifs-001.gif' ],
folders: [ 'folder/', 'folder2/' ] }
And that
s3ls({bucket: 'my-bucket-name'}).ls('/folder', console.log);
will print
{ files: [ 'folder/cv.docx' ],
folders: [ 'folder/sub-folder/' ] }
UPD: The latest version supports async/await Promise interface:
const { files, folders } = await lister.ls("/my-folder/subfolder/");
And here is the s3ls.js
:
var _ = require('lodash');
var S3 = require('aws-sdk').S3;
module.exports = function (options) {
var bucket = options.bucket;
var s3 = new S3({apiVersion: '2006-03-01'});
return {
ls: function ls(path, callback) {
var prefix = _.trimStart(_.trimEnd(path, '/') + '/', '/');
var result = { files: [], folders: [] };
function s3ListCallback(error, data) {
if (error) return callback(error);
result.files = result.files.concat(_.map(data.Contents, 'Key'));
result.folders = result.folders.concat(_.map(data.CommonPrefixes, 'Prefix'));
if (data.IsTruncated) {
s3.listObjectsV2({
Bucket: bucket,
MaxKeys: 2147483647, // Maximum allowed by S3 API
Delimiter: '/',
Prefix: prefix,
ContinuationToken: data.NextContinuationToken
}, s3ListCallback)
} else {
callback(null, result);
}
}
s3.listObjectsV2({
Bucket: bucket,
MaxKeys: 2147483647, // Maximum allowed by S3 API
Delimiter: '/',
Prefix: prefix,
StartAfter: prefix // removes the folder name from the file listing
}, s3ListCallback)
}
};
};