Created
March 18, 2024 13:20
-
-
Save bn-l/52d921b878e0fbb6d0a73b3d6f8091df to your computer and use it in GitHub Desktop.
Using minipass to create a regex transform stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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