Skip to content

Commit

Permalink
refactor: use the got module instead of the request module
Browse files Browse the repository at this point in the history
  • Loading branch information
lc-soft committed May 7, 2021
1 parent ddd78c4 commit 1102cbf
Show file tree
Hide file tree
Showing 3 changed files with 203 additions and 355 deletions.
46 changes: 19 additions & 27 deletions lib/create.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const fs = require('fs-extra');
const stream = require('stream');
const { promisify } = require('util');
const path = require('path');
const chalk = require('chalk');
const filesize = require('filesize');
const request = require('request');
const progress = require('request-progress');
const got = require('got');
const decompress = require('decompress');
const { execSync } = require('child_process');
const cliProgress = require('cli-progress');
Expand All @@ -17,41 +17,33 @@ function updateJSONFile(file, callback) {
fs.writeFileSync(file, JSON.stringify(callback(data), null, 2), 'utf-8');
}

function download() {
let started = false;
let fileSize = 0;
async function download() {
const pipeline = promisify(stream.pipeline);
const url = TEMPLATE_REPO_URL;
const filePath = `${TEMPLATE_REPO_NAME}.zip`;
const tmpFilePath = `${filePath}.download`;
const bar = new cliProgress.Bar({
format: '[{bar}] {percentage}% | {value}/{total} | {speed}/s'
format: '[{bar}] {percentage}% | {value}/{total}'
}, cliProgress.Presets.shades_classic);

if (fs.existsSync(filePath)) {
return Promise.resolve(filePath);
}
console.log('Downloading template project package');
return new Promise((resolve, reject) => {
progress(request(url))
.on('progress', (state) => {
if (!started) {
fileSize = state.size.total;
bar.start(state.size.total || '-', state.size.transferred);
started = true;
bar.start('-', 0);
await pipeline(
got.stream(url)
.on('downloadProgress', (progress) => {
bar.update(progress.transferred);
if (progress.total) {
bar.setTotal(progress.total);
}
bar.update(state.size.transferred, {
speed: filesize(state.speed || 0)
});
})
.on('error', reject)
.on('end', () => {
bar.update(fileSize);
bar.stop();
fs.renameSync(tmpFilePath, filePath);
resolve(filePath);
})
.pipe(fs.createWriteStream(tmpFilePath));
});
}),
fs.createWriteStream(tmpFilePath)
);
bar.stop();
fs.renameSync(tmpFilePath, filePath);
return filePath;
}

class Creator {
Expand Down
Loading

0 comments on commit 1102cbf

Please sign in to comment.