Skip to content

Commit b4592bc

Browse files
show progress in Kb if necessary
1 parent c69c63a commit b4592bc

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

src/upload.ts

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ export default class Upload {
3636
const fileName = path.basename(filePath);
3737
const fileStats = await fs.promises.stat(filePath);
3838
const totalSize = fileStats.size;
39-
const sizeMB = (totalSize / (1024 * 1024)).toFixed(2);
4039

4140
const progressTracker = progress({
4241
length: totalSize,
@@ -46,13 +45,13 @@ export default class Upload {
4645
let lastPercent = 0;
4746

4847
if (showProgress) {
49-
this.drawProgressBar(fileName, sizeMB, 0);
48+
this.drawProgressBar(fileName, totalSize, 0);
5049

5150
progressTracker.on('progress', (prog) => {
5251
const percent = Math.round(prog.percentage);
5352
if (percent !== lastPercent) {
5453
lastPercent = percent;
55-
this.drawProgressBar(fileName, sizeMB, percent);
54+
this.drawProgressBar(fileName, totalSize, percent);
5655
}
5756
});
5857
}
@@ -93,7 +92,7 @@ export default class Upload {
9392
const result = response.data;
9493
if (result.id) {
9594
if (showProgress) {
96-
this.drawProgressBar(fileName, sizeMB, 100);
95+
this.drawProgressBar(fileName, totalSize, 100);
9796
console.log('');
9897
}
9998
return { id: result.id };
@@ -124,20 +123,36 @@ export default class Upload {
124123

125124
private drawProgressBar(
126125
fileName: string,
127-
sizeMB: string,
126+
totalBytes: number,
128127
percent: number,
129128
): void {
130129
const barWidth = 30;
131130
const filled = Math.round((barWidth * percent) / 100);
132131
const empty = barWidth - filled;
133132
const bar = '█'.repeat(filled) + '░'.repeat(empty);
134-
const transferred = ((percent / 100) * parseFloat(sizeMB)).toFixed(2);
133+
134+
const transferredBytes = (percent / 100) * totalBytes;
135+
const transferred = this.formatFileSize(transferredBytes);
136+
const total = this.formatFileSize(totalBytes);
135137

136138
process.stdout.write(
137-
`\r ${fileName}: [${bar}] ${percent}% (${transferred}/${sizeMB} MB)`,
139+
`\r ${fileName}: [${bar}] ${percent}% (${transferred}/${total})`,
138140
);
139141
}
140142

143+
/**
144+
* Format file size in human-readable format (KB for small files, MB for larger)
145+
*/
146+
private formatFileSize(bytes: number): string {
147+
if (bytes < 1024) {
148+
return `${bytes} B`;
149+
} else if (bytes < 1024 * 1024) {
150+
return `${(bytes / 1024).toFixed(1)} KB`;
151+
} else {
152+
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
153+
}
154+
}
155+
141156
private async validateFile(filePath: string): Promise<void> {
142157
try {
143158
await fs.promises.access(filePath, fs.constants.R_OK);

0 commit comments

Comments
 (0)