-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·120 lines (89 loc) · 2.23 KB
/
app.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/env node
'use strict';
var s3 = require('s3'),
bucket,
objects = [],
toDelete = [];
var client = s3.createClient({
s3Options: {
accessKeyId: process.env.S3_ACCESS_KEY,
secretAccessKey: process.env.S3_SECRET,
region: process.env.S3_REGION || 'us-east-1'
},
});
/**
* Helpers
**/
function printUsage(err) {
console.log('\r\nempty-s3-bucket version 0.1.0.');
console.log('\r\n usage: empty-s3-bucket <bucket_name>');
console.log('\r\nReads Amazon AWS settings from env.S3_ACCESS_KEY and S3_SECRET or from local config.js file, fetches a list of objects and deletes them.');
if(err) {
console.log('\r\nThere were errors in your request: \r\n\r\n', err);
}
}
function extractKeys() {
console.log('Got objects, extracting keys...');
var length = objects.length;
if(!length) {
return;
}
for(var i = 0; i < length; i++) {
toDelete.push({Key: objects[i].Key});
}
}
function deleteFiles() {
var length = toDelete.length;
console.log('Deleting ' + length + ' files...');
if(!length) {
printUsage('No files to delete, bucket empty.');
process.exit(0);
}
var s3Params = {
Bucket: bucket,
Delete: {
Objects: toDelete
}
};
var s3 = client.deleteObjects(s3Params);
s3.on('error', function(err) {
printUsage(err);
});
s3.on('end', function() {
console.log('Bucket emptied.');
});
}
function getListOfObjects() {
console.log('Getting list of objects...');
var s3 = client.listObjects({
recursive: true,
s3Params: {
Bucket: bucket
}
}, function(err, data) {
console.log('s3 params callback');
console.log(err || data);
});
s3.on('error', function(err) {
printUsage(err);
process.exit(1);
});
s3.on('data', function(data) {
if(data.Contents) {
objects = objects.concat(data.Contents);
}
});
s3.on('end', function() {
extractKeys();
deleteFiles();
});
}
/**
* start
**/
bucket = process.argv[2];
if(!bucket) {
printUsage('Please specify bucket.');
process.exit(0);
}
getListOfObjects();