node js Streams are collections of data โ just like arrays or strings. The difference is that streams might not be available all at once, and they donโt have to fit in memory. This makes streams really powerful when working with large amounts of data, or data thatโs coming from an external source one chunk at a time.
|
|
fs.createReadStream()
allows you to open up a readable stream in a very simple manner. All you have to do is pass the path of the file to start streaming in. It turns out that the response (as well as the request) objects are streams.
|
|
this will consume you pc memory.
|
|
The fs.readFile()
function buffers the entire file. To minimize memory costs, when possible prefer streaming via fs.createReadStream()
.
|
|
this will read the file.txt
['We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
[ 'We want change.' ]
for 1 million time
|
|
now the above code is not in a stream and would not recommend it in an istance where your dealling with over a million lines or lage file as wi have .
But insteady we can create createReadStream()
to create a http server that streams the files to the client. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary
|
|
check out this post from node for more