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

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software