-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathprogress.mjs
43 lines (38 loc) · 890 Bytes
/
progress.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// @ts-check
/**
* @typedef {object} ProgressTracker
* @prop {string} value
* @prop {() => void} end
*/
/**
* @template T
* @param {string} initial
* @param {(update: (val: string) => void) => Promise<T>} task
* @returns {Promise<T>}
*/
export async function progress(initial, task) {
const ciMode =
typeof process.stdout.clearLine !== 'function' ||
typeof process.stdout.cursorTo !== 'function';
if (ciMode) {
console.log(initial);
return await task((val) => {
console.log(val);
});
}
process.stdout.write(initial);
try {
return await task((val) => {
if (
process.stdout.clearLine &&
typeof process.stdout.clearLine === 'function'
) {
process.stdout.clearLine(0);
}
process.stdout.cursorTo(0);
process.stdout.write(val);
});
} finally {
process.stdout.write('\n');
}
}