What is a stream?

A stream in Node.js is an abstract interface that processes stream data. The STREAM module provides the basic API. Using these apis, you can easily build objects that implement the flow interface.

Node.js provides a variety of stream objects. For example, HTTP requests and process.stdout are instances of flows.

Streams can be readable, writable, or read-write. All streams are instances of EventEmitter.

A stream is an abstract data structure. Imagine water flowing through a pipe so that it can flow from one place (like a waterworks) to another (like your sink). We can also think of data as a stream of data, like when you type on a keyboard, you can think of each character as a stream of characters.

There are four basic stream types in Node.js:

  • Readable-a stream that is Readable (for example, fs.createreadStream ()).
  • Writable – Writable stream (for example fs.createWritestream ()).
  • Duplex – A read-write stream (such as net.socket).
  • Transform – A Duplex stream that can modify and Transform data during reading and writing (for example, zlib.createDeflate()).


All stream objects created using the Node.js API can only manipulate strings and Buffer (or Uint8Array) objects. However, with some third-party stream implementations, you can still handle other types of JavaScript values (besides null, which has special meaning in stream processing). These streams are said to work in object mode.

Readable

Readable events:

Readable: An event will be emitted when there is data available to read from the stream. In some cases, adding a callback for the ‘readable’ event will cause some data to be read into the internal cache.

Data: Events are triggered when the flow passes data to the consumer. This event is triggered when the flow transitions to flowing mode. Calling the readable.pipe(), readable.resume() method, or adding a callback to the ‘data’ event can convert the stream to flowing mode. The ‘data’ event is also emitted when the readable.read() method is called and data is returned.

End: The event will fire when there is no more data in the stream to consume.

Close: When the underlying resource, such as a file, is closed.

Error: An error in receiving data is triggered.

Readable method:

Read ([size]): Reads data from the stream. The data can be String, Buffer, or NULL (as the code below does), and when size is specified, the read-only value is limited to that number of bytes

SetEncoding (encoding) : Sets the encoding used in the read() request to read the mandatory String

Pause (): Pauses data events emitted from this object

Resume (): Resumes the data event emitted from this object

Create a Readable stream:

let fs = require('fs'); let path = require('path'); Let rs = fs.createreadstream (path.join(__dirname,'1.txt'),{flags:'r', // The file is read. Encoding :'utf8', Buffer autoClose:true; highWaterMark:3; // Default: 64K; 64*1024b; // 123 456 789 //end:9 Rs.setencoding ('utf8'); rs.setencoding ('utf8'); Rs.on ('open',function(){console.log(' file open')}); // newLisenterrs.on('data',function(data){// Pause mode -> flow mode console.log(data); // rs.pause(); // pause the data event}); Rs. on('readable',function(res){console.log(' there is data '); }); rs.on('error',function(err){ console.log(err); }); rs.on('end',function(){ console.log('end')}); Rs.on ('close',function(){console.log(' close')});Copy the code

0123456789 Data available End closedCopy the code

Writable

Writable events:

Write (chunk,[encoding],[callback]) : Writes data to the stream. Chunk contains the data to be written to,encoding specifies the encoding of the string, and callback specifies a callback function to execute when the data has been completely flushed. Write () returns true if the write succeeds.

End ([chunk],[encoding],[callback]): As with write(), it sets the Writable object to a state that no longer accepts data and sends the Finish event.

Writable method:

Drain: After the write() call returns false, this event notifies the monitor when it is ready to start writing more data.

Finish: Fired when end() is called on a Writable object, so the data is flushed and no more data is accepted


Create a Writable:

let fs = require('fs');let path = require('path'); // Create a file when the file does not existlet ws = fs.createWriteStream(path.join(__dirname,'1.txt'),{    highWaterMark:3,    autoClose:true,    flags:'w',    encoding:'utf8', mode:0o666, start:0,}); Bufferfor (var I = 0; i<4; i++){let flag =  ws.write(i+' '); // Write a character console.log(flag)}ws.on('drain'.function(){    console.log('drain')});Copy the code

Console printing:true true falseFalsedrain1.txt contains 0123Copy the code