refactor: refork tail module

This commit is contained in:
2026-10-22 12:04:40 +03:00
parent a421d56ec1
commit 84d905dbb3
12 changed files with 1047 additions and 2036 deletions
+31 -48
View File
@@ -1,68 +1,51 @@
import { Transform, Writable } from "stream";
import { Transform, Writable, type TransformCallback, type WritableOptions } from "stream";
import { StringDecoder } from "string_decoder";
import { Tail } from "tail";
import through from "through2";
import Vinyl from "vinyl";
export class TailVinyl extends Vinyl {
constructor(params: any) {
params.contents = new Transform();
super(params);
if (params.path) {
this.tail = new Tail(params.path);
(this.tail.on("line", (line) => {
if (params.handler) {
line = params.handler(line);
}
if (line) {
this.contents.write(line + "\n");
}
}),
this.tail.on("error", (error: any) => this.contents.write("error: " + error)));
}
}
export type TailHandler = (line: string) => void;
dispose() {
if (this.tail) {
this.tail.unwatch();
}
this.contents.destroy();
}
}
export class HandlerWriter extends Writable {
private handler: any;
private decoder: StringDecoder;
private data: string;
export class StringWritable extends Writable {
constructor(handler: any, options?: any) {
constructor(handler: TailHandler, options?: WritableOptions) {
if (!options) options = {};
options.objectMode = true;
super(options);
this.handler = handler;
const state = this._writableState;
this._decoder = new StringDecoder(state.defaultEncoding);
this.decoder = new StringDecoder(options?.defaultEncoding);
this.data = "";
}
_write(chunk, encoding, callback) {
if (encoding === "buffer") {
chunk = this._decoder.write(chunk);
for (const line of chunk.split("\n"))
if (line.length) {
this.handler(line);
}
_write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void {
chunk = this.decoder.write(chunk);
for (const line of chunk.split("\n")) {
if (line.length) {
this.handler(line);
}
}
this.data += chunk;
callback();
}
_final(callback) {
this.data += this._decoder.end();
_final(callback: (error?: Error | null) => void): void {
this.data += this.decoder.end();
callback();
}
}
export const tail = (handler: any) => {
return through.obj(function (file: any, enc: string, callback: any) {
if (file.contents && file.contents.pipe) {
file.contents.pipe(new StringWritable(handler));
export class TailTransform extends Transform {
constructor(private handler: TailHandler) {
super({ objectMode: true });
}
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
if (chunk.contents && chunk.contents.pipe) {
chunk.contents.pipe(new HandlerWriter(this.handler));
}
this.push(file);
this.push(chunk);
callback();
});
};
}
}
export const tail = (handler: TailHandler) => new TailTransform(handler);