Capturing Data from an EventEmitter

EventEmitter is a very important class in Node.[11] It provides a channel for events to be dispatched and listeners notified. Many objects you’ll encounter in Node inherit from EventEmitter, like the Streams we saw in the last section.

Now let’s modify our previous program to capture the child process’s output by listening for events on the stream. Open an editor to the watcher-spawn.js file from the previous section, then find the call to fs.watch(). Replace it with this:

file-system/watcher-spawn-parse.js
​ 
fs.watch(filename, ​function​() {
​ 
​let​
​ 
ls = spawn(​'ls'​, [​'-lh'​, filename]),
​ 
output = ​''​;
​ 
ls.stdout.on(​'data'​, ​function​(chunk){
​ 
output ...

Get Node.js the Right Way now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.