From f0a335c02b3435bc8ec1771a40e5fec32f826fcf Mon Sep 17 00:00:00 2001 From: Samuel Torres <33882985+torressam333@users.noreply.github.com> Date: Mon, 30 Sep 2024 10:03:15 -0700 Subject: [PATCH] Update index.js to properly find files Without the updated way of reading the file path node.js is always throwing an error that the file cannot be found: ``` Error emitted ENOENT: no such file or directory, open 'fileA.txt' Error emitted ENOENT: no such file or directory, open 'fileB.json' ``` The way the txt and json files are found needs to be updated as indicated in the code change proposal. --- .../09-eventemitter-find-regex/index.js | 52 ++++++++++--------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/03-callbacks-and-events/09-eventemitter-find-regex/index.js b/03-callbacks-and-events/09-eventemitter-find-regex/index.js index 8b348f47..8720dc8d 100644 --- a/03-callbacks-and-events/09-eventemitter-find-regex/index.js +++ b/03-callbacks-and-events/09-eventemitter-find-regex/index.js @@ -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}`));