-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmega.js
More file actions
58 lines (51 loc) · 1.79 KB
/
Copy pathmega.js
File metadata and controls
58 lines (51 loc) · 1.79 KB
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
const mega = require('megajs');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const config = require('./config.js');
function randomName(ext) {
return `${crypto.randomBytes(5).toString('hex')}${ext || '.json'}`;
}
function upload(input, name) {
return new Promise((resolve, reject) => {
let content;
let fileName = name || randomName('.json');
if (typeof input === 'string') {
const filePath = path.resolve(input);
if (!fs.existsSync(filePath)) {
return reject(new Error(`Session file not found: ${filePath}`));
}
content = fs.readFileSync(filePath);
if (!name) {
fileName = randomName(path.extname(filePath) || '.json');
}
} else if (Buffer.isBuffer(input)) {
content = input;
} else {
return reject(new Error('Upload expects a file path or buffer'));
}
const storage = new mega.Storage({
email: config.EMAIL,
password: config.PASS
}, (err) => {
if (err) {
return reject(err);
}
try {
const stream = storage.upload({
name: fileName,
size: content.length,
allowUploadBuffering: true
});
stream.end(content);
stream.on('complete', (file) => {
file.link((linkErr, url) => (linkErr ? reject(linkErr) : resolve(url)));
});
stream.on('error', reject);
} catch (error) {
reject(error);
}
});
});
}
module.exports = { upload };