Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update index.js to properly find files #81

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 28 additions & 24 deletions 03-callbacks-and-events/09-eventemitter-find-regex/index.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
import { EventEmitter } from 'events'
import { readFile } from 'fs'
import { EventEmitter } from "events";
import { readFile } from "fs";
import path from "path";

function findRegex (files, regex) {
const emitter = new EventEmitter()
for (const file of files) {
readFile(file, 'utf8', (err, content) => {
if (err) {
return emitter.emit('error', err)
}
// Resolve __dirname using import.meta.url (node 16)
const __dirname = path.dirname(new URL(import.meta.url).pathname);

emitter.emit('fileread', file)
const match = content.match(regex)
if (match) {
match.forEach(elem => emitter.emit('found', file, elem))
}
})
}
return emitter
const filePathA = path.join(__dirname, "fileA.txt");
const filePathB = path.join(__dirname, "fileB.json");

function findRegex(files, regex) {
const emitter = new EventEmitter();
for (const file of files) {
readFile(file, "utf8", (err, content) => {
if (err) {
return emitter.emit("error", err);
}

emitter.emit("fileread", file);
const match = content.match(regex);
if (match) {
match.forEach((elem) => emitter.emit("found", file, elem));
}
});
}
return emitter;
}

findRegex(
['fileA.txt', 'fileB.json'],
/hello \w+/g
)
.on('fileread', file => console.log(`${file} was read`))
.on('found', (file, match) => console.log(`Matched "${match}" in ${file}`))
.on('error', err => console.error(`Error emitted ${err.message}`))
findRegex([filePathA, filePathB], /hello \w+/g)
.on("fileread", (file) => console.log(`${file} was read`))
.on("found", (file, match) => console.log(`Matched "${match}" in ${file}`))
.on("error", (err) => console.error(`Error emitted ${err.message}`));