@devteks/downloader
Version:
Simple node.js file downloader
159 lines (158 loc) • 5.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const __1 = require("../");
const url_1 = require("url");
const path_1 = require("path");
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const NC = '\x1b[0m';
const RED = '\x1b[0;31m';
const GREEN = '\x1b[0;32m';
const YELLOW = '\x1b[0;33m';
const BLUE = '\x1b[0;34m';
const MAGENTA = '\x1b[0;35m';
const CYAN = '\x1b[0;36m';
const CMD = 'download';
const UNITS = ['b', 'kB', 'MB', 'GB', 'TB'];
const KB = 1024;
const _color = (color, text) => `${color}${text}${NC}`;
const _r = (text) => _color(RED, text);
const _g = (text) => _color(GREEN, text);
const _y = (text) => _color(YELLOW, text);
const _b = (text) => _color(BLUE, text);
const _m = (text) => _color(MAGENTA, text);
const _c = (text) => _color(CYAN, text);
const print = (...args) => console.log(...args);
const printProgress = (buffer) => {
process.stdout.clearLine(-1);
process.stdout.cursorTo(0);
process.stdout.write(buffer);
};
const fmtSize = (v) => {
if (v === 0)
return '0 b';
const p = Math.floor(Math.log(v) / Math.log(KB));
const n = (v / Math.pow(KB, Math.floor(p))).toFixed(1);
return `${n} ${UNITS[p]}`;
};
// dest default to process.cwd();
const getArgs = () => {
const args = process.argv.slice(2);
if (args.indexOf('-v') > -1 || args.indexOf('--version') > -1) {
const pkg = require('../../package.json');
print(`${_m(CMD)} v${pkg.version}`);
return;
}
if (args.length < 1) {
print(`${_b('USAGE:')} $ ${_m(CMD)} ${_y('[dir]')} ${_y('url')}
${_y('dir')}: ${_b('destination folder to download the file to (optional).')}
${_y('url')}: ${_b('remote url to download.')}
`);
return;
}
let dest = '';
let url = '';
if (args.length === 1) {
dest = process.cwd();
url = args[0];
}
else {
dest = args[0];
url = args[1];
}
if (!(0, fs_1.existsSync)(dest)) {
print(_r('Please use an existing folder or valid path'));
return;
}
try {
new url_1.URL(url);
}
catch (ex) {
print(_r('Please use a valid URL'));
return;
}
return { url, dest };
};
function main() {
return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {
const args = getArgs();
if (!args)
return;
const { url, dest } = args;
let progressLog = '';
const downloader = new __1.Downloader(url, dest, {
headers: {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
},
});
let totalSize = 0;
let fileName = '';
let fullPath = '';
try {
const result = yield downloader.getTotalSize();
fileName = result.name;
totalSize = result.total;
fullPath = (0, path_1.join)(dest, fileName);
}
catch (ex) {
print(_r(`Can not reach ${url}`), ex);
return;
}
try {
const s = yield (0, promises_1.stat)(fullPath);
if (s.size == totalSize) {
print(_g(`File ${fileName} already fully downloaded`));
return;
}
}
catch (ex) { }
downloader.on('end', (s) => {
printProgress(progressLog + ' - ' + _g('Download Completed'));
});
downloader.on('retry', (s) => {
let count = Math.floor(s.delay / 1000);
const retryLog = () => {
printProgress(_b(`Retry Attempt: `) + _y(`${s.retryCount}/${s.maxRetries} | Starts on: ${count} secs`));
if (count > 0)
setTimeout(() => retryLog(), 1000);
count--;
};
retryLog();
});
downloader.on('renamed', (s) => {
fileName = s.fileName;
fullPath = (0, path_1.join)(dest, fileName);
//print(`RENAMED:`, s);
print(_b(`File already exists, renamed to:`), _y(fileName));
});
downloader.on('download', (s) => {
print(_b(`Start downloading:`), _m(url));
print(_b(`Saved as:`), _c(fileName), _y(`( ${fmtSize(totalSize)} )`));
print();
});
downloader.on('resume', (isResumed) => {
if (!isResumed) {
print(_y("\nURL doesn't support resume, it will start from the beginning"));
}
});
downloader.on('progressThrottled', (s) => {
progressLog = ([
_m(s.progress.toFixed(1) + '%'),
' ',
_y(`[${fmtSize(s.downloaded)}/${fmtSize(s.total)}]`),
' ',
_c(fmtSize(s.speed) + '/s'),
]).join(' ');
printProgress(progressLog);
});
try {
yield downloader.start();
}
catch (ex) {
print(_r('Something happend'), ex);
}
});
}
main();
//# sourceMappingURL=command.js.map