66 lines
1.6 KiB
TypeScript
66 lines
1.6 KiB
TypeScript
import { Transform, type TransformCallback } from "stream";
|
|
import { Tail } from "tail";
|
|
import Vinyl from "vinyl";
|
|
|
|
export type WatchHandler = (line: string) => string | undefined;
|
|
|
|
export interface WatchParams {
|
|
source: string;
|
|
handler?: WatchHandler;
|
|
}
|
|
|
|
class BufferingTransform extends Transform {
|
|
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
|
|
this.push(chunk);
|
|
callback();
|
|
}
|
|
}
|
|
export class TailVinyl extends Vinyl {
|
|
private tail?: Tail;
|
|
|
|
constructor(params: WatchParams) {
|
|
super({ path: "out.log", contents: new BufferingTransform() });
|
|
if (params.source) {
|
|
this.tail = new Tail(params.source);
|
|
this.tail.on("line", (line) => {
|
|
if (params.handler) {
|
|
line = params.handler(line);
|
|
}
|
|
if (line) {
|
|
this.contents.write(line + "\n");
|
|
}
|
|
});
|
|
this.tail.on("error", (error) => this.contents.write("error: " + error));
|
|
}
|
|
}
|
|
|
|
clone() {
|
|
return new Vinyl({
|
|
cwd: this.cwd,
|
|
base: this.base,
|
|
history: this.history.slice(),
|
|
contents: this.contents,
|
|
});
|
|
}
|
|
|
|
dispose() {
|
|
this.tail?.unwatch();
|
|
this.contents.destroy();
|
|
}
|
|
}
|
|
|
|
export class WatchVinylTransform extends Transform {
|
|
constructor(private params: WatchParams) {
|
|
super({ objectMode: true });
|
|
}
|
|
|
|
_transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void {
|
|
const log = new TailVinyl(this.params);
|
|
this.on("end", () => log.dispose());
|
|
this.push(log);
|
|
callback();
|
|
}
|
|
}
|
|
|
|
export const watch = (source: string, handler?: WatchHandler) => new WatchVinylTransform({ source, handler });
|