Skip to content

Instantly share code, notes, and snippets.

@keighty
Created October 16, 2016 15:42
Show Gist options
  • Select an option

  • Save keighty/b8eabffe9cdee79ab8338a899e256377 to your computer and use it in GitHub Desktop.

Select an option

Save keighty/b8eabffe9cdee79ab8338a899e256377 to your computer and use it in GitHub Desktop.
Node EventEmitter example
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
*/
hello blah blah blah
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment