-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaxiosRequest.js
More file actions
78 lines (71 loc) · 2.18 KB
/
axiosRequest.js
File metadata and controls
78 lines (71 loc) · 2.18 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import axios from 'axios';
import fs from 'fs';
import extract from 'extract-zip';
import path from 'path';
//define some global variables
let link = '';
let file = '';
let outputDirectory = path.resolve('../../plugins/');
let finished = true;
//request the download link for the latest version of the wordpress plugin, based on the slug
async function downloadPlugin(slug) {
finished = false;
await axios.get(`https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&slug=${slug}`)
.then(function (response) {
//save the server response to a global variable nd return it
link = response.data.download_link;
console.log(`Download link: ${link}`);
getFile(slug);
})
.catch(function (error) { //catch any errors
console.log(error);
})
return;
}
//make a GET request to whatever download link line 15 returns
async function getFile(slug) {
await axios({
method: 'get',
url: `${link}`,
responseType: 'stream',
onDownloadProgress: function (progressEvent) {
console.log(`Downloading ${slug}: ${(progressEvent.progress*100).toFixed(2)}%`);
}
})
.then(function(response) {
const writer = fs.createWriteStream(`../../plugins/${slug}.zip`);
//capture the server response into a data stream and pipe it into a new file in the plugins directory
response.data.pipe(writer).on('finish', (err) => {
if (err) throw err;
file = `../../plugins/${slug}.zip`
console.log('Download complete!');
decompressFile(file);
})
})
return file;
}
//unzip the file into the directory that Wordpress is expecting
async function decompressFile(file) {
console.log('Extracting...');
try {
await extract(file, { dir: outputDirectory })
console.log('Extraction complete')
} catch (err) {
// handle any errors
console.log(err);
}
await cleanup(file);
return;
}
//delete the old zip after extraction completes
async function cleanup(file) {
console.log('Cleaning up...')
fs.unlink(file, () => {
console.log('Cleanup successful.');
finished = true;
// console.log('Build complete. Thanks for using Themegen!');
})
return;
}
// export download function
export {downloadPlugin, finished};