How to do it...

A good way to start understanding how streams work is to look at how Node core uses them.

The core fs module has a createReadStream method; let's use that to make a read stream:

const fs = require('fs') 
const rs = fs.createReadStream(__filename)

The __filename variable is provided by Node. It holds the absolute path of the file currently being executed (in our case, it will point to the index.js file in the self-read folder).

The first thing to notice is that this method appears to be synchronous.

Normally, when we work with I/O in Node, we have to provide a callback. Streams abstract this away by returning an object instance that represents the entire contents of the file.

How do we get the file data out of this abstraction? One way to extract data from a stream is by listening to the data event.

Let's attach a data listener that will be called every time a new small chunk of the file has been read:

rs.on('data', (data) => { 
console.log('Read chunk:', data)
})

rs.on('end', () => {
console.log('No more data')
})

When we are done reading the file, the stream will emit an end event.

Let's try this out:

$ node index.js