Before we continue, I think a brief detour to cover some basics of Node streams would be helpful.
Lets create a simple Node script to read a index.html file we will create:
1 2 3 4 5 6 7 8 9 | |
First we require the file system library fs and create a read stream.
1 2 | |
_dirname is a helper that returns the absolute path of the code file being run.
Node reads files asynchronously. This is normally where we could dive into what “non-blocking I/O” means vs threads, etc. This is a guide about gulp though so I will keep this detour basic.
For our purposes, this means that we have to listen to events from the stream to be able to read the file.
The events we are going to listen to are data and end.
data fires when a chunk of the file has been read and returned. This chunk is not always the entire file. In fact, you should assume it is not the entire file.
1 2 3 4 5 | |
end fires when the file has been completly read.
1 2 3 4 5 | |
Now altogether, streams.js looks like:
1 2 3 4 5 6 7 8 9 10 | |
Now if you run the node script in the terminal, you should see:
1 2 3 4 5 6 7 8 9 10 11 12 | |
So far so good, That’s it!!! See ya!!! :)