k6-node
Version:
CLI tool that enables k6 installation via npm packages
73 lines (72 loc) • 3.19 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.downloadFile = void 0;
const node_path_1 = __importDefault(require("node:path"));
const node_fs_1 = __importDefault(require("node:fs"));
const pipes_1 = require("../utils/pipes");
const node_http_1 = __importDefault(require("node:http"));
const node_https_1 = __importDefault(require("node:https"));
/**
* Download a file with progress bar
*/
const downloadFile = async (url, outputPath) => {
return new Promise((resolve, reject) => {
const tmpPath = outputPath + '.download';
const protocol = url.startsWith('https') ? node_https_1.default : node_http_1.default;
const dir = node_path_1.default.dirname(outputPath);
if (!node_fs_1.default.existsSync(dir)) {
node_fs_1.default.mkdirSync(dir, { recursive: true });
}
protocol
.get(url, (response) => {
if (response.statusCode === 302) {
// handle github redirect ;)
(0, exports.downloadFile)(response.headers.location, outputPath)
.then(resolve)
.catch(reject);
return;
}
if (response.statusCode !== 200) {
reject(new Error(`Failed to download: ${response.statusCode} ${response.statusMessage}`));
return;
}
const totalSize = parseInt(response.headers['content-length'], 10);
let downloadedSize = 0;
let lastProgress = 0;
const fileStream = node_fs_1.default.createWriteStream(tmpPath);
const updateProgress = () => {
const progress = totalSize ? (downloadedSize / totalSize) * 100 : 0;
const progressBarLength = 30;
const filledLength = Math.round((progressBarLength * progress) / 100);
const bar = '#'.repeat(filledLength) +
'-'.repeat(progressBarLength - filledLength);
if (progress - lastProgress >= 1 || Date.now() - lastProgress > 100) {
process.stdout.write(`\r-> Downloading: [${bar}] ${progress.toFixed(1)}% | ${(0, pipes_1.formatBytes)(downloadedSize)}/${(0, pipes_1.formatBytes)(totalSize)}`);
lastProgress = progress;
}
};
response.on('data', (chunk) => {
downloadedSize += chunk.length;
updateProgress();
});
response.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
node_fs_1.default.renameSync(tmpPath, outputPath);
process.stdout.write('\n');
resolve(outputPath);
});
fileStream.on('error', (err) => {
node_fs_1.default.unlink(tmpPath, () => { });
reject(err);
});
})
.on('error', (err) => {
reject(err);
});
});
};
exports.downloadFile = downloadFile;