Skip to content

Instantly share code, notes, and snippets.

@bn-l
Created March 18, 2024 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bn-l/52d921b878e0fbb6d0a73b3d6f8091df to your computer and use it in GitHub Desktop.
Save bn-l/52d921b878e0fbb6d0a73b3d6f8091df to your computer and use it in GitHub Desktop.
Using minipass to create a regex transform stream
import { Minipass } from "minipass";
export class RegexPipe extends Minipass<string, string> {
public regex: RegExp;
protected hasGroup: boolean;
private buffer: string = "";
constructor({ regex, hasGroup }: { regex: RegExp; hasGroup: boolean }) {
super({ encoding: "utf8" });
this.regex = regex;
this.hasGroup = hasGroup;
}
// Write is overloaded (for some reason) so cb needs to be any.
// Otherwise needs to override the overloads. What a mess.
override write(chunk: string, callback: any) {
this.buffer += chunk;
let match: RegExpExecArray | null;
let extracted = "";
while (match = this.regex.exec(this.buffer)) {
this.buffer = this.buffer.slice(this.regex.lastIndex);
this.regex.lastIndex = 0;
extracted += match[1] + "\n";
}
return super.write(extracted, callback);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment