refactor: rewrite on typescript
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
import { Transform, Writable } 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)));
|
||||
}
|
||||
}
|
||||
|
||||
dispose() {
|
||||
if (this.tail) {
|
||||
this.tail.unwatch();
|
||||
}
|
||||
this.contents.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
export class StringWritable extends Writable {
|
||||
constructor(handler: any, options?: any) {
|
||||
super(options);
|
||||
this.handler = handler;
|
||||
const state = this._writableState;
|
||||
this._decoder = new StringDecoder(state.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);
|
||||
}
|
||||
}
|
||||
this.data += chunk;
|
||||
callback();
|
||||
}
|
||||
|
||||
_final(callback) {
|
||||
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));
|
||||
}
|
||||
this.push(file);
|
||||
callback();
|
||||
});
|
||||
};
|
||||
Reference in New Issue
Block a user