Streams
Streams
https://www.geeksforgeeks.org/what-is-stream-and-its-types-in-node-js/
Concept of streams and buffers is the sole foundation of most of the
mid-to-low level programming languages.
Stream, on the other hand, differs from the buffer in the way it
consumes data chunks. Streams can read/write data chunk by chunk,
without buffering the whole file at once. In other words, if you read a
textfile.txt where you have :
“My name is Doctor Watson”
It is possible to consume the file at the pace of byte by byte (as 1
character is a byte) that allows you to grab, transform and display the
contents of the file, byte by byte, progressively, like this:
“character: M”
“character: y”
“character: “
“character: n”
(…)
Each character progressively, gradually taken from the file and
transformed, without buffering the whole textfile.txt in a upfront fashion.
Stream can be progressively loaded data with no definite
length specified. Speaking of the above example in this context; it stores
each chunk of data in temporary allocated memory, instead of the whole,
definite sized buffer.
Streams also use buffers (typically), to store content streamed so far, and
when the stream is done, that buffer gets freed somewhere (examples: in
case of reading, freed up in the output device, case of writing; writing to
the disk).
The heart of streams and buffers of Nodejs lies in C++ <iostream>
library, as Nodejs is built in mainly C++ (some of the code in C as well).
II. Nodejs: Example of setting up a the stream, will (later) take data
chunk by chunk:
4.var stream = fs.createReadStream(__dirname + '/filename.txt');
4 types of stream
1. Readable
2. Writable
3. Duplex
4. Transforms
rs.on("data",(chunkdata)=>{
res.write(chunkdata);
});
rs.on("end",()=>{
res.end();
});
rs.on("error",(err)=>{
console.log(err);
res.end("File not Found");
});
}).listen(8000,"127.0.0.1");
var fs = require('fs');
var data = 'This is a code to learn“ + " about writing in a stream.';
On console window ‘the end’ will print more than one time.
rs.on('data',function(datachunk){
console.log("the end")
ws.write(datachunk);
})
var fs = require('fs');
console.log('File Compressed.');
var fs = require('fs');
var zlib = require('zlib');
console.log('File Decompressed.');