O'Reilly logo

Node.js 8 the Right Way by Jim Wilson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Capturing Data from an EventEmitter

EventEmitter is a very important class in Node.js. It provides a channel for events to be dispatched and listeners to be notified. Many objects you’ll encounter in Node.js 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:

 fs.watch(filename, () => {
 const​ ls = spawn(​'ls'​, [​'-l'​, ​'-h'​, filename]);
 let​ output = ​''​;
 
  ls.stdout.on(​'data'​, chunk => output += chunk);
 
  ls.on(​'close'​, () => {
  ​ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required