Home Web Front-end JS Tutorial Introduction to Stream in Node.js_node.js

Introduction to Stream in Node.js_node.js

May 16, 2016 pm 04:07 PM
node.js stream flow

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:

Copy code The code is as follows:

//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.

The

Stream class, in the Node.js source code , is defined as follows:

Copy code The code is 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:

Copy code The code is as follows:

process.stdin.on('readable', function(){
var buf = process.stdin.read();
if(buf){
var data = buf.toString();
// parsing data ...                                                   }
});

Call like this:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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:

Copy code The code is as follows:

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

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

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

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

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!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

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.

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

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!

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

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".

How to debug Java Stream operations in IntelliJ IDEA How to debug Java Stream operations in IntelliJ IDEA May 09, 2023 am 11:25 AM

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.

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

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

An article to talk about how to efficiently develop presentation layer Node.js applications An article to talk about how to efficiently develop presentation layer Node.js applications Apr 17, 2023 pm 07:02 PM

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.

See all articles