hdm-cli 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -6
- package/dist/cli.js +61 -14
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -2
- package/dist/progress.d.ts +21 -3
- package/dist/progress.js +77 -24
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ hdm(Hyper Download Manager)是一个小巧的 Node.js 多连接文件下载
|
|
|
6
6
|
- 下载中断后可以从断点继续
|
|
7
7
|
- 连接掉线、卡住或请求失败时自动重试
|
|
8
8
|
- 显示进度条、下载速度和剩余时间
|
|
9
|
-
- 没有运行时依赖,发布包约
|
|
9
|
+
- 没有运行时依赖,发布包约 13 kB
|
|
10
10
|
|
|
11
11
|
需要 Node.js 20 或更高版本。
|
|
12
12
|
|
|
@@ -45,13 +45,28 @@ hdm -o ~/Downloads https://example.com/file.zip
|
|
|
45
45
|
hdm -c 16 -H "Authorization: Bearer TOKEN" https://example.com/file.zip
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
+
下载过程中:
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
文件 file.zip
|
|
52
|
+
位置 ~/Downloads
|
|
53
|
+
大小 24.0 MB
|
|
54
|
+
连接 8 个
|
|
55
|
+
|
|
56
|
+
━━━━━━━━━━━━━━━━━━━━━━──────────────────────────────────── 39.5%
|
|
57
|
+
9.50 MB / 24.0 MB 8.54 MB/s 剩余 0:02 用时 0:02 连接 8
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
完成后,进度条会被一行结果替换:
|
|
61
|
+
|
|
48
62
|
```
|
|
49
|
-
|
|
50
|
-
██████████████████████████████░░░░░░░░░░ 75.0% 18.0 MB / 24.0 MB 8.66 MB/s ETA 0:01
|
|
51
|
-
已保存 file.zip(24.0 MB,用时 0:03,平均 8.40 MB/s)
|
|
63
|
+
✔ 下载完成 24.0 MB 用时 0:03 平均 8.40 MB/s
|
|
52
64
|
```
|
|
53
65
|
|
|
54
|
-
进度条只在输出到终端时绘制。在管道或 CI
|
|
66
|
+
- 进度条只在输出到终端时绘制。在管道或 CI 日志里,只打印开头的文件信息和结尾的结果。
|
|
67
|
+
- 终端较窄时,会从右往左省略统计项,过长的文件名从中间截断。
|
|
68
|
+
- 设置环境变量 `NO_COLOR=1` 可以关闭颜色。
|
|
69
|
+
- 所有信息都输出到标准错误。
|
|
55
70
|
|
|
56
71
|
### 断点续传
|
|
57
72
|
|
|
@@ -108,7 +123,7 @@ const { path, size } = await download('https://example.com/file.zip', {
|
|
|
108
123
|
| `connections` | `number` | 本次下载使用的连接数。 |
|
|
109
124
|
| `resumable` | `boolean` | 中断后能否续传。 |
|
|
110
125
|
|
|
111
|
-
`onProgress` 收到 `{ downloaded, total }
|
|
126
|
+
`onProgress` 收到 `{ downloaded, total, connections }`。`downloaded` 和 `total` 的单位是字节,`downloaded` 包含续传前已有的字节;`connections` 是仍在传输数据的连接数。
|
|
112
127
|
|
|
113
128
|
### 取消下载
|
|
114
129
|
|
package/dist/cli.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
|
-
import {
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { basename, dirname, sep } from 'node:path';
|
|
4
5
|
import { parseArgs } from 'node:util';
|
|
5
6
|
import { download } from './index.js';
|
|
6
|
-
import { createProgressBar, formatBytes, formatDuration } from './progress.js';
|
|
7
|
+
import { createPaint, createProgressBar, displayWidth, formatBytes, formatDuration, } from './progress.js';
|
|
7
8
|
const MAX_CONNECTIONS = 32;
|
|
8
9
|
const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
|
|
9
10
|
// The command name shown in messages is the one package.json installs.
|
|
@@ -77,11 +78,15 @@ for (const line of values.header) {
|
|
|
77
78
|
const ctl = new AbortController();
|
|
78
79
|
// Only the first Ctrl-C is handled, so a second one still kills the process outright.
|
|
79
80
|
process.once('SIGINT', () => ctl.abort());
|
|
81
|
+
const paint = createPaint();
|
|
82
|
+
/** Prints one line of the layout: a dimmed label, then its value. */
|
|
83
|
+
const row = (label, value) => console.error(` ${paint('dim', label)} ${value}`);
|
|
80
84
|
const started = Date.now();
|
|
81
85
|
let info;
|
|
82
86
|
let bar;
|
|
87
|
+
let downloaded = 0;
|
|
83
88
|
try {
|
|
84
|
-
const {
|
|
89
|
+
const { size } = await download(url, {
|
|
85
90
|
output: values.output,
|
|
86
91
|
connections,
|
|
87
92
|
headers,
|
|
@@ -89,30 +94,72 @@ try {
|
|
|
89
94
|
signal: ctl.signal,
|
|
90
95
|
onStart(start) {
|
|
91
96
|
info = start;
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
97
|
+
downloaded = start.resumed;
|
|
98
|
+
console.error();
|
|
99
|
+
row('文件', fit(basename(start.path)));
|
|
100
|
+
row('位置', fit(tildify(dirname(start.path))));
|
|
101
|
+
row('大小', start.total === null ? '未知' : formatBytes(start.total));
|
|
102
|
+
row('连接', start.resumable ? `${start.connections} 个` : '1 个(服务器不支持分片,中断后无法续传)');
|
|
103
|
+
if (start.resumed)
|
|
104
|
+
row('续传', `已有 ${formatBytes(start.resumed)}${percent(start.resumed)}`);
|
|
105
|
+
console.error();
|
|
95
106
|
bar = createProgressBar(start.total, start.resumed);
|
|
96
107
|
},
|
|
97
|
-
onProgress
|
|
108
|
+
onProgress(progress) {
|
|
109
|
+
downloaded = progress.downloaded;
|
|
110
|
+
bar?.update(progress);
|
|
111
|
+
},
|
|
98
112
|
});
|
|
99
113
|
bar?.stop();
|
|
100
114
|
const seconds = (Date.now() - started) / 1000;
|
|
101
115
|
const speed = formatBytes((size - (info?.resumed ?? 0)) / Math.max(seconds, 0.001));
|
|
102
|
-
|
|
116
|
+
const took = `${paint('dim', '用时')} ${formatDuration(seconds)}`;
|
|
117
|
+
const summary = [formatBytes(size), took, `${paint('dim', '平均')} ${speed}/s`].join(' ');
|
|
118
|
+
console.error(` ${paint('green', '✔')} ${paint('bold', '下载完成')} ${summary}`);
|
|
103
119
|
}
|
|
104
120
|
catch (err) {
|
|
105
121
|
bar?.stop();
|
|
106
122
|
if (ctl.signal.aborted) {
|
|
107
|
-
|
|
123
|
+
const got = `${paint('dim', '已下载')} ${formatBytes(downloaded)}${percent(downloaded)}`;
|
|
124
|
+
console.error(` ${paint('yellow', '■')} ${paint('bold', '已中断')} ${got}`);
|
|
125
|
+
if (info?.resumable)
|
|
126
|
+
console.error(' 再次运行同一条命令即可续传。');
|
|
108
127
|
process.exit(130);
|
|
109
128
|
}
|
|
110
129
|
const { message, cause } = err;
|
|
111
130
|
// fetch reports network failures as a bare "fetch failed" with the real reason in `cause`.
|
|
112
|
-
|
|
131
|
+
const reason = cause instanceof Error ? `请求失败:${cause.message}` : message;
|
|
132
|
+
// Before the header is printed there is no layout to match, so use the plain "command: message" form.
|
|
133
|
+
if (!info)
|
|
134
|
+
fail(reason);
|
|
135
|
+
console.error(` ${paint('red', '✖')} ${paint('bold', '下载失败')} ${reason}`);
|
|
136
|
+
process.exit(1);
|
|
137
|
+
}
|
|
138
|
+
/** Formats `bytes` as a share of the file, or as nothing when the size is unknown. */
|
|
139
|
+
function percent(bytes) {
|
|
140
|
+
return info?.total ? `(${((bytes / info.total) * 100).toFixed(1)}%)` : '';
|
|
113
141
|
}
|
|
114
|
-
/**
|
|
115
|
-
function
|
|
116
|
-
const
|
|
117
|
-
return
|
|
142
|
+
/** Replaces the home directory at the start of a path with "~". */
|
|
143
|
+
function tildify(path) {
|
|
144
|
+
const home = homedir();
|
|
145
|
+
return path === home || path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path;
|
|
146
|
+
}
|
|
147
|
+
/** Shortens text that would not fit beside a label on one terminal line, cutting from the middle. */
|
|
148
|
+
function fit(text) {
|
|
149
|
+
if (!process.stderr.isTTY)
|
|
150
|
+
return text;
|
|
151
|
+
const room = (process.stderr.columns || 80) - 9;
|
|
152
|
+
if (displayWidth(text) <= room)
|
|
153
|
+
return text;
|
|
154
|
+
const chars = [...text];
|
|
155
|
+
let head = Math.ceil(chars.length / 2);
|
|
156
|
+
let tail = chars.length - head;
|
|
157
|
+
const join = () => `${chars.slice(0, head).join('')}…${chars.slice(chars.length - tail).join('')}`;
|
|
158
|
+
while (head + tail > 0 && displayWidth(join()) > room) {
|
|
159
|
+
if (head >= tail)
|
|
160
|
+
head--;
|
|
161
|
+
else
|
|
162
|
+
tail--;
|
|
163
|
+
}
|
|
164
|
+
return join();
|
|
118
165
|
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -60,7 +60,7 @@ async function downloadStream(req, path, options) {
|
|
|
60
60
|
req.alive();
|
|
61
61
|
await writeAll(file, chunk, downloaded);
|
|
62
62
|
downloaded += chunk.length;
|
|
63
|
-
options.onProgress?.({ downloaded, total });
|
|
63
|
+
options.onProgress?.({ downloaded, total, connections: 1 });
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
66
|
finally {
|
|
@@ -96,6 +96,7 @@ async function downloadRanges(url, headers, path, total, probe, ctl, options) {
|
|
|
96
96
|
}
|
|
97
97
|
const pending = state.segments.filter((seg) => seg.done < seg.end - seg.start + 1);
|
|
98
98
|
let downloaded = state.segments.reduce((sum, seg) => sum + seg.done, 0);
|
|
99
|
+
let active = pending.length;
|
|
99
100
|
options.onStart?.({ path, total, resumed: downloaded, connections: pending.length, resumable: true });
|
|
100
101
|
const fetchRange = async (seg, file) => {
|
|
101
102
|
const from = seg.start + seg.done;
|
|
@@ -122,7 +123,7 @@ async function downloadRanges(url, headers, path, total, probe, ctl, options) {
|
|
|
122
123
|
await writeAll(file, chunk, seg.start + seg.done);
|
|
123
124
|
seg.done += chunk.length;
|
|
124
125
|
downloaded += chunk.length;
|
|
125
|
-
onProgress?.({ downloaded, total });
|
|
126
|
+
onProgress?.({ downloaded, total, connections: active });
|
|
126
127
|
}
|
|
127
128
|
}
|
|
128
129
|
finally {
|
|
@@ -151,6 +152,7 @@ async function downloadRanges(url, headers, path, total, probe, ctl, options) {
|
|
|
151
152
|
if (seg.done < size)
|
|
152
153
|
await sleep(Math.min(250 * 2 ** failures, 15_000), undefined, { signal });
|
|
153
154
|
}
|
|
155
|
+
active--;
|
|
154
156
|
}
|
|
155
157
|
finally {
|
|
156
158
|
await file.close();
|
package/dist/progress.d.ts
CHANGED
|
@@ -1,9 +1,27 @@
|
|
|
1
|
+
import type { Progress } from './index.js';
|
|
1
2
|
export interface ProgressBar {
|
|
2
|
-
update(
|
|
3
|
-
/**
|
|
3
|
+
update(progress: Progress): void;
|
|
4
|
+
/** Erases the display, so the caller can print a closing line in its place. */
|
|
4
5
|
stop(): void;
|
|
5
6
|
}
|
|
6
|
-
|
|
7
|
+
declare const STYLES: {
|
|
8
|
+
bold: number;
|
|
9
|
+
dim: number;
|
|
10
|
+
red: number;
|
|
11
|
+
green: number;
|
|
12
|
+
yellow: number;
|
|
13
|
+
cyan: number;
|
|
14
|
+
};
|
|
15
|
+
export type Paint = (style: keyof typeof STYLES, text: string) => string;
|
|
16
|
+
/** Returns a function that colours text, or leaves it plain when `out` is not a colour terminal. */
|
|
17
|
+
export declare function createPaint(out?: NodeJS.WriteStream): Paint;
|
|
18
|
+
/** Terminal columns `text` occupies: CJK and full-width characters take two. */
|
|
19
|
+
export declare function displayWidth(text: string): number;
|
|
20
|
+
/**
|
|
21
|
+
* A two-line progress display: a bar with the percentage, and a row of figures under it.
|
|
22
|
+
* Draws nothing when `out` is not a terminal.
|
|
23
|
+
*/
|
|
7
24
|
export declare function createProgressBar(total: number | null, initial?: number, out?: NodeJS.WriteStream): ProgressBar;
|
|
8
25
|
export declare function formatBytes(bytes: number): string;
|
|
9
26
|
export declare function formatDuration(seconds: number): string;
|
|
27
|
+
export {};
|
package/dist/progress.js
CHANGED
|
@@ -1,49 +1,102 @@
|
|
|
1
1
|
const REFRESH_MS = 100;
|
|
2
|
-
/** Speed is averaged over this window so the reading and the
|
|
2
|
+
/** Speed is averaged over this window so the reading and the time remaining do not jitter. */
|
|
3
3
|
const SPEED_WINDOW_MS = 3000;
|
|
4
|
-
const MAX_BAR_WIDTH = 40;
|
|
5
4
|
const MIN_BAR_WIDTH = 10;
|
|
6
|
-
|
|
5
|
+
const INDENT = ' ';
|
|
6
|
+
const GAP = ' ';
|
|
7
|
+
const STYLES = { bold: 1, dim: 2, red: 31, green: 32, yellow: 33, cyan: 36 };
|
|
8
|
+
/** Returns a function that colours text, or leaves it plain when `out` is not a colour terminal. */
|
|
9
|
+
export function createPaint(out = process.stderr) {
|
|
10
|
+
const enabled = out.isTTY && !process.env.NO_COLOR && process.env.TERM !== 'dumb';
|
|
11
|
+
return (style, text) => (enabled ? `\x1b[${STYLES[style]}m${text}\x1b[0m` : text);
|
|
12
|
+
}
|
|
13
|
+
const WIDE = /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{1f300}-\u{1faff}\u{20000}-\u{3fffd}]/u;
|
|
14
|
+
/** Terminal columns `text` occupies: CJK and full-width characters take two. */
|
|
15
|
+
export function displayWidth(text) {
|
|
16
|
+
let width = 0;
|
|
17
|
+
for (const char of text)
|
|
18
|
+
width += WIDE.test(char) ? 2 : 1;
|
|
19
|
+
return width;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A two-line progress display: a bar with the percentage, and a row of figures under it.
|
|
23
|
+
* Draws nothing when `out` is not a terminal.
|
|
24
|
+
*/
|
|
7
25
|
export function createProgressBar(total, initial = 0, out = process.stderr) {
|
|
8
26
|
if (!out.isTTY)
|
|
9
27
|
return { update() { }, stop() { } };
|
|
28
|
+
const paint = createPaint(out);
|
|
29
|
+
const started = Date.now();
|
|
10
30
|
let downloaded = initial;
|
|
11
|
-
|
|
12
|
-
const
|
|
31
|
+
let connections = 0;
|
|
32
|
+
const samples = [[started, initial]];
|
|
33
|
+
const frame = () => {
|
|
13
34
|
const now = Date.now();
|
|
14
35
|
samples.push([now, downloaded]);
|
|
15
36
|
while (samples.length > 2 && now - samples[0][0] > SPEED_WINDOW_MS)
|
|
16
37
|
samples.shift();
|
|
17
38
|
const [since, base] = samples[0];
|
|
18
39
|
const speed = now > since ? ((downloaded - base) * 1000) / (now - since) : 0;
|
|
19
|
-
//
|
|
20
|
-
const
|
|
21
|
-
|
|
40
|
+
// Each figure is padded to a fixed width, so the ones after it do not shift as it changes.
|
|
41
|
+
const figures = [
|
|
42
|
+
total
|
|
43
|
+
? { value: `${formatBytes(downloaded)} / ${formatBytes(total)}`, width: 11 + formatBytes(total).length }
|
|
44
|
+
: { value: formatBytes(downloaded), width: 8 },
|
|
45
|
+
{ value: `${formatBytes(speed)}/s`, width: 10 },
|
|
46
|
+
];
|
|
22
47
|
if (total) {
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
const percent = (Math.floor(ratio * 1000) / 10).toFixed(1).padStart(5);
|
|
26
|
-
const eta = speed > 0 ? formatDuration((total - downloaded) / speed) : '--:--';
|
|
27
|
-
line = `${percent}% ${formatBytes(downloaded)} / ${formatBytes(total)} ${formatBytes(speed)}/s ETA ${eta}`;
|
|
28
|
-
const width = Math.min(MAX_BAR_WIDTH, columns - line.length - 2);
|
|
29
|
-
if (width >= MIN_BAR_WIDTH) {
|
|
30
|
-
const filled = Math.floor(ratio * width);
|
|
31
|
-
line = `${'█'.repeat(filled)}${'░'.repeat(width - filled)} ${line}`;
|
|
32
|
-
}
|
|
48
|
+
const left = speed > 0 ? formatDuration((total - downloaded) / speed) : '--:--';
|
|
49
|
+
figures.push({ label: '剩余', value: left, width: 10 });
|
|
33
50
|
}
|
|
34
|
-
|
|
35
|
-
|
|
51
|
+
figures.push({ label: '用时', value: formatDuration((now - started) / 1000), width: 10 });
|
|
52
|
+
if (connections)
|
|
53
|
+
figures.push({ label: '连接', value: String(connections), width: 7 });
|
|
54
|
+
// Stay one column short of the edge so the terminal never wraps a line.
|
|
55
|
+
const room = (out.columns || 80) - 1 - INDENT.length;
|
|
56
|
+
let stats = '';
|
|
57
|
+
let statsWidth = 0;
|
|
58
|
+
let column = 0;
|
|
59
|
+
for (const { label, value, width } of figures) {
|
|
60
|
+
const size = displayWidth(label ? `${label} ${value}` : value);
|
|
61
|
+
if (column + size > room)
|
|
62
|
+
break;
|
|
63
|
+
stats += ' '.repeat(column - statsWidth) + (label ? `${paint('dim', label)} ${value}` : value);
|
|
64
|
+
statsWidth = column + size;
|
|
65
|
+
column += Math.max(width, size) + GAP.length;
|
|
66
|
+
}
|
|
67
|
+
if (!total)
|
|
68
|
+
return [INDENT + stats];
|
|
69
|
+
const ratio = Math.min(1, downloaded / total);
|
|
70
|
+
// Floored, so the display only reads 100% once every byte has arrived.
|
|
71
|
+
const percent = `${(Math.floor(ratio * 1000) / 10).toFixed(1)}%`.padStart(6);
|
|
72
|
+
// The bar and its percentage span the same width as the figures below them.
|
|
73
|
+
const barWidth = statsWidth - percent.length - 2;
|
|
74
|
+
if (barWidth < MIN_BAR_WIDTH)
|
|
75
|
+
return [INDENT + percent.trim(), INDENT + stats];
|
|
76
|
+
const filled = Math.floor(ratio * barWidth);
|
|
77
|
+
const bar = paint('cyan', '━'.repeat(filled)) + paint('dim', '─'.repeat(barWidth - filled));
|
|
78
|
+
return [`${INDENT}${bar} ${paint('bold', percent)}`, INDENT + stats];
|
|
79
|
+
};
|
|
80
|
+
let drawn = 0;
|
|
81
|
+
/** Moves back to the first line of the previous frame. */
|
|
82
|
+
const rewind = () => (drawn > 1 ? `\x1b[${drawn - 1}A\r` : '\r');
|
|
83
|
+
const render = () => {
|
|
84
|
+
const lines = frame();
|
|
85
|
+
// One write per frame, so the terminal never shows a half-drawn one.
|
|
86
|
+
out.write(rewind() + lines.map((line) => `${line}\x1b[K`).join('\n') + '\x1b[J');
|
|
87
|
+
drawn = lines.length;
|
|
36
88
|
};
|
|
37
89
|
const timer = setInterval(render, REFRESH_MS);
|
|
38
90
|
render();
|
|
39
91
|
return {
|
|
40
|
-
update(
|
|
41
|
-
downloaded =
|
|
92
|
+
update(progress) {
|
|
93
|
+
downloaded = progress.downloaded;
|
|
94
|
+
connections = progress.connections;
|
|
42
95
|
},
|
|
43
96
|
stop() {
|
|
44
97
|
clearInterval(timer);
|
|
45
|
-
|
|
46
|
-
|
|
98
|
+
out.write(`${rewind()}\x1b[J`);
|
|
99
|
+
drawn = 0;
|
|
47
100
|
},
|
|
48
101
|
};
|
|
49
102
|
}
|
package/package.json
CHANGED