Created
October 16, 2016 15:42
-
-
Save keighty/b8eabffe9cdee79ab8338a899e256377 to your computer and use it in GitHub Desktop.
Node EventEmitter example
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
| const EventEmitter = require('events').EventEmitter | |
| const fs = require('fs') | |
| const findPattern = (files, regex) => { | |
| const emitter = new EventEmitter() | |
| files.forEach(file => { | |
| fs.readFile(file, 'utf8', (err, content) => { | |
| if (err) return emitter.emit('error', err) | |
| emitter.emit('fileread', file) | |
| let match | |
| if (match = content.match(regex)) { | |
| match.forEach(elem => { | |
| emitter.emit('found', file, elem) | |
| }) | |
| } | |
| }) | |
| }) | |
| return emitter | |
| } | |
| const files = ['fileA.txt', 'fileB.json', 'fileC.md'] | |
| findPattern(files, /hello \w+/g) | |
| .on('fileread', file => {console.log(`${file} was read`)}) | |
| .on('found', (file, match) => {console.log(`Matched ${match} in file ${file}`)}) | |
| .on('error', err => {console.log(`Error emitted: ${err.message}`)}) | |
| /* | |
| $ node --use_strict events.js | |
| Error emitted: ENOENT: no such file or directory, open 'fileC.md' | |
| fileB.json was read | |
| fileA.txt was read | |
| Matched hello blah in file fileA.txt | |
| */ |
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
| hello blah blah blah |
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
| {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment