Introduction to Stream in Node.js_node.js
What is flow?
Speaking of streams, it involves a *nix concept: Pipe - In *nix, streams are implemented in the Shell as data that can be bridged through | (pipe character), a The output of a process (stdout) can be directly used as the input (stdin) of the next process.
In Node, the concept of stream (Stream) is similar, representing the ability of a data stream to be bridged.
pipe
The essence of streaming lies in the .pipe() method. The ability to bridge is that both ends of the data stream (upstream/downstream or read/write stream) are bridged with a .pipe() method.
The expression form of pseudo code is:
//upstream.pipe (downstream)
Readable.pipe(Writable);
Classification of streams
This is not intended to discuss the so-called "classic" flow before Node v0.4. Then, streams are divided into several categories (all abstract interfaces:
1.stream.Readable Readable stream (needs to implement the _read method, the focus is on the details of reading the data stream
2.stream.Writable Writable stream (needs to implement the _write method, the focus is on the details of writing the data stream
3.stream.Duplex Read/write stream (needs to implement the above two interfaces, focus on the details of the above two interfaces
4.stream.Transform Inherited from Duplex (needs to implement the _transform method, the focus is on the processing of data blocks
In short:
1) The owner of .pipe() must have Readable stream (but not limited to) capability. It has a series of 'readable'/'data'/'end'/'close'/'error' events for Subscription also provides a series of methods such as .read()/.pause()/.resume() for calling;
2) The parameters of .pipe() must have Writable stream capabilities (but not limited to). It has 'drain'/'pipe'/'unpipe'/'error'/'finish' events for access, and also provides .write ()/.end() and other methods are available for calling
What the hell
Are you feeling the slightest bit anxious? Don't worry, as a low-level coder who speaks human language, I will break Stream apart and talk to you about it.
TheStream class, in the Node.js source code , is defined as follows:
var EE = require('events').EventEmitter;
var util = require('util');
util.inherits(Stream, EE);
function Stream() {
EE.call(this);
}
As you can see, essentially, Stream is an EventEmitter, which means that it has event-driven functions (.emit/.on...). As we all know, "Node.js is an event-driven platform based on V8", which implements event-driven streaming programming and has the same asynchronous callback characteristics as Node.
For example, in a Readable stream, there is a readable event. In a paused read-only stream, as long as a data block is ready to be read, it will be sent to the subscriber (what are the Readable streams? Express) req, req.part of ftp or mutli-form upload component, standard input process.stdin in the system, etc.). With the readable event, we can make a tool such as a parser that processes shell command output:
process.stdin.on('readable', function(){
var buf = process.stdin.read();
if(buf){
var data = buf.toString();
// parsing data ... }
});
Call like this:
head -10 some.txt | node parser.js
For a Readable stream, we can also subscribe to its data and end events to get chunks of data and get notified when the stream is exhausted, as in the classic socket example:
req.on('connect', function(res, socket, head) {
socket.on('data', function(chunk) {
console.log(chunk.toString());
});
socket.on('end', function() {
proxy.close();
});
});
Readable stream status switching
It should be noted that the Readable stream has two states: flowing mode (torrent) and pause mode (pause). The former cannot stop at all, and will continue to feed whoever is piped; the latter will pause until the downstream explicitly calls Stream.read() request to read the data block. The Readable stream is in pause mode when initialized.
These two states can be switched between each other, among which,
If any of the following behaviors occur, pause will change to flowing:
1. Add a data event subscription to the Readable stream
2. Call .resume() on Readable to explicitly enable flowing
3. Call .pipe(writable) of the Readable stream to bridge to a Writable stream
If any of the following behaviors occurs, flowing will return to pause:
1.Readable stream has not been piped to any stream yet, adjustable .pause() can be used to pause
2. The Readable stream has been piped to the stream. You need to remove all data event subscriptions and call the .unpipe() method to release the relationship with the downstream stream one by one
Wonderful Use
Combined with the asynchronous characteristics of the stream, I can write an application like this: directly bridge the output of user A to the output on the page of user B:
router.post('/post', function(req, res) {
var destination = req.headers['destination']; //Who to send to
cache[destionation] = req;
//Yes, it does not return, so it is best to make an ajax request
});
When user B requests:
router.get('/inbox', function(req, res){
var user = req.headers['user'];
cache.find(user, function(err, previousReq){ //Find the previously saved req
var form = new multiparty.Form();
form.parse(previousReq); // There are files for me
form.on('part', function (part) {
part.pipe(res); //Streaming method is good:)
part.on('error', function (err) {
console.log(err);
messaging.setRequestDone(uniqueID);
return res.end(err);
});
});
});
});
Reference
how to write node programs with streams: stream-handbook

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

Stream operation is a highlight of Java8! Although java.util.stream is very powerful, there are still many developers who rarely use it in actual work. One of the most complained reasons is that it is difficult to debug. This was indeed the case at the beginning, because streaming operations such as stream cannot be used in DEBUG When it is one line of code, when it comes to the next step, many operations are actually passed at once, so it is difficult for us to judge which line in it is the problem. Plug-in: JavaStreamDebugger If the IDEA version you are using is relatively new, this plug-in is already included and does not need to be installed. If it is not installed yet, install it manually and then continue below.

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

How to use Node.js for front-end application development? The following article will introduce you to the method of developing front-end applications in Node, which involves the development of presentation layer applications. The solution I shared today is for simple scenarios, aiming to allow front-end developers to complete some simple server-side development tasks without having to master too much background knowledge and professional knowledge about Node.js, even if they have no coding experience.
