-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
53 lines (42 loc) · 1.37 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { readFile } from "fs";
import { EventEmitter } from "events";
import type { PathOrFileDescriptor } from "fs";
interface EventsMap {
error: [Error];
read: [PathOrFileDescriptor];
match: [PathOrFileDescriptor, string, string];
start: [PathOrFileDescriptor[]];
}
class RegexFinder extends EventEmitter<EventsMap> {
private regex: RegExp;
private files: string[];
constructor(files: string[], regexPattern: string) {
super();
if (!regexPattern) this.emit("error", new Error("No regex provided"));
this.regex = new RegExp(regexPattern, "g");
this.files = files;
}
find() {
process.nextTick(() => this.emit("start", this.files));
for (const file of this.files) {
readFile(file, "utf-8", (error, data) => {
if (error) {
return this.emit("error", error);
}
this.emit("read", file);
const match = data.match(this.regex);
if (match) {
match.forEach((element) => this.emit("match", file, element, data));
}
});
}
return this;
}
}
const finder = new RegexFinder(["fileB.json", "fileA.txt"], process.argv[2]);
finder
.find()
.on("start", (files) => console.log("Started", files))
.on("error", (error) => console.error(error))
.on("read", (file) => console.log(`${file} was read`))
.on("match", (file, data) => console.log(`Match on ${file} -> ${data}`));