node-console-progress-bar-tqdm
Version:
Progress bar in console for Node.js in the style of TQDM Python library
106 lines • 2.79 kB
JavaScript
import { EOL } from 'node:os';
import tty from 'node:tty';
import { getTermClearScreen, getTermReturnToLineStart } from './term.js';
import { hasFd } from './utils.js';
const defaultTerminalColumns = 80;
export class TqdmNumericIterator {
num;
cnt = 0;
constructor(num) {
this.num = num;
}
next() {
const val = this.cnt++;
if (val >= this.num) {
return { value: undefined, done: true };
}
return { value: val, done: false };
}
}
export class TqdmSyncResultIterator {
container;
constructor(container) {
this.container = container;
}
next() {
return this.container.nextSync();
}
}
export class TqdmAsyncResultIterator {
container;
constructor(container) {
this.container = container;
}
next() {
return this.container.nextAsync();
}
}
export class TqdmWriteStream {
stream;
resetLine;
streamIsTty;
constructor(stream, forceTerminal = false) {
this.stream = stream;
this.resetLine = this.generalResetLine;
this.streamIsTty = stream instanceof tty.WriteStream && hasFd(stream) && tty.isatty(stream.fd);
if (this.streamIsTty) {
this.resetLine = this.ttyResetLine;
process.once('SIGWINCH', this.onTerminalResize);
}
else if (forceTerminal) {
this.resetLine = this.forceTerminalResetLine;
}
}
get isTty() {
return this.streamIsTty;
}
get columns() {
const stream = this.getStreamAsTty();
if (stream) {
return stream.columns;
}
return defaultTerminalColumns;
}
write(chunk) {
this.stream.write(chunk);
}
finalize() {
process.off('SIGWINCH', this.onTerminalResize);
this.stream.write(EOL);
}
clearScreen() {
const stream = this.getStreamAsTty();
if (stream) {
stream.write(EOL);
stream.write(getTermClearScreen());
stream.cursorTo(0, 0);
}
}
onTerminalResize = () => {
this.clearScreen();
process.once('SIGWINCH', this.onTerminalResize);
};
getStreamAsTty() {
if (this.stream instanceof tty.WriteStream) {
return this.stream;
}
return null;
}
ttyResetLine = () => {
const stream = this.getStreamAsTty();
if (stream) {
stream.clearLine(0);
stream.cursorTo(0);
}
else {
this.forceTerminalResetLine();
}
};
forceTerminalResetLine = () => {
this.stream.write(getTermReturnToLineStart());
};
generalResetLine = () => {
this.stream.write(EOL);
};
}
//# sourceMappingURL=supply.js.map