-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
55 lines (48 loc) · 1.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const trimStart = (s, ch) => (s[0] === ch ? trimStart(s.substr(1), ch) : s);
const trimEnd = (s, ch) =>
s[s.length - 1] === ch ? trimEnd(s.substr(0, s.length - 1), ch) : s;
module.exports = function S3LS(options) {
if (!options || typeof options.bucket !== "string") {
throw new Error("Bad 'bucket'");
}
const bucket = options.bucket;
const s3 =
options.s3 || new (require("aws-sdk")).S3({ apiVersion: "2006-03-01" });
return {
ls(path) {
const prefix = trimStart(trimEnd(path, "/") + "/", "/");
const result = { files: [], folders: [] };
function s3ListCheckTruncated(data) {
result.files = result.files.concat(
(data.Contents || []).map(i => i.Key)
);
result.folders = result.folders.concat(
(data.CommonPrefixes || []).map(i => i.Prefix)
);
if (data.IsTruncated) {
return s3
.listObjectsV2({
Bucket: bucket,
MaxKeys: 2147483647, // Maximum allowed by S3 API
Delimiter: "/",
Prefix: prefix,
ContinuationToken: data.NextContinuationToken
})
.promise()
.then(s3ListCheckTruncated);
}
return result;
}
return s3
.listObjectsV2({
Bucket: bucket,
MaxKeys: 2147483647, // Maximum allowed by S3 API
Delimiter: "/",
Prefix: prefix,
StartAfter: prefix // removes the folder name from listing
})
.promise()
.then(s3ListCheckTruncated);
}
};
};