pinetto
Version:
Isomorphic, opinionated logging library focusing on simplicity and readability. Supports child loggers.
46 lines • 1.48 kB
JavaScript
import { EMPTY, RESOLVED, IS_NODE, EOL } from '../constants.js';
export class BufferedWriter {
#buffer;
#timeout;
#flushing;
#write;
#maxBufferLength;
#flushTimeout;
constructor(opts = EMPTY) {
this.#buffer = '';
this.#timeout = null;
this.#flushing = false;
this.#maxBufferLength = typeof opts.maxBufferLength === 'number' ? opts.maxBufferLength : 8192;
this.#flushTimeout = typeof opts.maxBufferLength === 'number' ? opts.flushTimeout : 250;
this._flush = this._flush.bind(this);
this.#write = IS_NODE
? (entry) => {
process.stdout.write(entry);
process.stdout.write(EOL.value);
}
: console.log.bind(console);
}
_flush() {
this.#write(this.#buffer);
this.#buffer = '';
if (this.#timeout) {
clearTimeout(this.#timeout);
this.#timeout = null;
}
this.#flushing = false;
}
write(entry) {
this.#buffer += entry + EOL.value;
if (!this.#flushing) {
if (this.#buffer.length >= this.#maxBufferLength) {
this.#flushing = true;
RESOLVED.then(this._flush);
}
else if (this.#timeout === null) {
this.#flushing = true;
this.#timeout = setTimeout(this._flush, this.#flushTimeout);
}
}
}
}
//# sourceMappingURL=buffered.js.map