-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3x.js
executable file
·139 lines (105 loc) · 2.96 KB
/
s3x.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#!/usr/bin/env node
const AWS = require('aws-sdk');
const fs = require('fs');
const async = require('async');
const mime = require('mime');
const program = require('commander');
async function getClient() {
let path = program.config || 's3x.config.js';
const configExists = fs.existsSync(path);
if (!configExists) {
throw new Error('No config file. (s3x.config.js)');
}
path = fs.realpathSync(path);
const config = require(path);
AWS.config.update({
accessKeyId: config.key,
secretAccessKey: config.secret,
region: config.region
});
return new AWS.S3({
params: {Bucket: config.bucket},
signatureVersion: 'v4'
});
}
function finish(err) {
if (err) {
console.error('[ERROR]', err);
return process.exit(1);
}
console.log('done');
process.exit(0);
}
program
.version('0.0.1')
.option('-c, --config <path>', 'Credentials (s3x.config.js)');
program.command('upload <from-fs> <to-s3>')
.action(async function (from, to) {
console.log('> upload', from, to);
try {
const client = await getClient();
await client.putObject({
Key: to,
Body: fs.createReadStream(from),
ContentType: mime.lookup(from)
}).promise();
finish();
} catch (err) {
finish(err);
}
});
program.command('download <s3-path> <fs-path>')
.action(async function (s3path, fsPath) {
try {
const client = await getClient();
const file = fs.createWriteStream(fsPath);
const readStream = client
.getObject({Key: s3path})
.createReadStream();
readStream.on('end', function () {
finish();
});
readStream.pipe(file);
} catch (err) {
finish(err);
}
});
program.command('ls [path]')
.action(async function (path) {
path = path || '/';
console.log('> ls', path);
try {
const client = await getClient();
let files = [];
let response = {
IsTruncated: true, Marker: path
};
async.whilst(
() => response.IsTruncated,
async () => {
const data = await client.listObjects({Marker: response.Marker}).promise();
const _as = data.Contents.map(function (img) {
return '/' + img.Key;
});
files = files.concat(_as);
response = data;
response.Marker = data.Contents[data.Contents.length - 1].Key;
},
(err) => {
if (err) {
return finish(err);
}
files.forEach(function (file) {
console.log(file);
});
finish();
}
);
} catch (err) {
finish(err);
}
});
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}