In-depth understanding of some features of Node. js, in-depth understanding of node. js

Source: Internet
Author: User

In-depth understanding of some features of Node. js, in-depth understanding of node. js

As an emerging background language, Node. js aims to help programmers quickly build scalable applications. Node. js has a lot of attractions, and there are countless reports on it. This article will analyze and discuss EventEmitter, Streams, Coding Style, Linting, Coding Style, and other features to help users with Node. js has a deeper understanding.

As a platform based on Chrome JavaScript runtime, our understanding of JavaScript seems to be applicable to node applications. No additional language extensions or modifications are required, we can apply the experience of frontend programming to backend programming.

EventEmitter (event sender)

First, you should first understand the EventEmitter model. It can send an event and subscribe to events that interest the consumer. We can regard it as an extension of the callback transfer mode to an asynchronous function. In particular, EventEmitter is more advantageous when multiple Callbacks are required.

For example, a caller sends a "List Files" request to the remote server. You may want to group the returned results and perform a callback for each group. The EventEmitter model allows you to send a "file" callback to each group. When all operations are completed, the "end" Callback is performed.

When using EventEmitter, you only need to set relevant events and parameters.

Copy codeThe Code is as follows:
Var EventEmitter = require ('events'). EventEmitter;
Var util = require ('til ');

Function MyClass (){
If (! (This instanceof MyClass) return new MyClass ();

EventEmitter. call (this );

Var self = this;
SetTimeout (function timeoutCb (){
Self. emit ('myevent', 'Hello world', 42 );
},1000 );
}
Util. inherits (MyClass, EventEmitter );

The MyClass constructor creates a time trigger with a trigger delay of 1 s and a trigger event of myEvent. To use related events, run the on () method:

Copy codeThe Code is as follows:
Var myObj = new MyClass ();
Var start = Date. now ();
MyObj. on ('myevent', function myEventCb (str, num ){
Console. log ('myevent triggered', str, num, Date. now ()-start );
});

Note that the subscribed EventEmitter event is an asynchronous event, but when the time is triggered, the listener's action is synchronized. Therefore, if the above myEvent event contains 10 listeners, all the listeners will be called in order without waiting for the loop of the event.

If an emit ('error') event is generated by a subclass of EventEmitter, but no listener subscribes to the event, the EventEmitter base class throws an exception, this triggers the uncaughtException event when the process object is executed.

Verror

Verror is an extension of the base class Error. We can use the printf character format to define the Output Message.

Streams)

If a very large file needs to be processed, the ideal method should be to read and write a part, regardless of the size of the file, as long as the time permits, it will always be processed, here we need to use the concept of stream. Streams is another widely used model in Node. It is an EventEmitter implementation in Node. Provides readable, writable, or full-duplex interfaces. It is an abstract interface that provides general operation events including readable, writable, drain, data, end, and close. If we can use pipelines to effectively integrate these events, we can achieve more powerful interactive operations.

By using. pipe (), Note can communicate with back-pressure through pipeline. Back-pressure means to read only those that can be written or only those that can be read.

For example, we now send data from stdin to a local file and remote server:
Copy codeThe Code is as follows:
Var fs = require ('fs ');
Var net = require ('net ');

Var localFile = fs. createWriteStream ('localfile. tmp ');

Net. connect ('2017. 00000000255', 255, function (client ){
Process. stdin. pipe (client );
Process. stdin. pipe (localFile );
});

If we want to send data to a local file and use gunzip to compress the stream, we can do this:

Copy codeThe Code is as follows:
Var fs = require ('fs ');
Var zlib = require ('zlib ');

Process.stdin.pipe(zlib.creategunzip(paipai.pipe(fs.createwritestream('localfile.tar '));

To learn more about stream, click here.

Control Flow)

Javascript has the first class object, closure, and other functional concepts, so it is easy to define the callback permission. This is very convenient for prototyping and can integrate logical permissions on demand. However, it is easy to use clumsy built-in functions.

For example, we want to read a series of files in order and then execute a task:
Copy codeThe Code is as follows:
Fs. readFile ('firstfile', 'utf8', function firstCb (err, firstFile ){
DoSomething (firstFile );
Fs. readFile ('secondfile', 'utf8', function secondCb (err, secondFile ){
DoSomething (secondFile );
Fs. readFile ('thirdfile', 'utf8', function thirdCb (err, thirdFile ){
DoSomething (thirdFile );
});
});
});

This mode has the following problems:

1. The logic of these codes is unorganized and difficult to understand.
2. No errors or exceptions are handled.
3. Closure Memory leakage in JS is very common and difficult to diagnose and detect.

If we want to perform a series of asynchronous operations on an input set, it is more wise to use a process control library. Vasync is used here.

Vasync is a process control library, and its idea comes from asynchronous operations. It allows consumers to view and observe the processing of a task. This information is useful for studying the process of generating an error.

Coding Style)

Programming style is the most controversial topic, because it is often casual. Radish cabbage, each with love. It is important to find a style suitable for individuals and teams. Some traditional inheritance may make the Node development journey better.

1. Name the Function
2. Try to name all functions.
3. Avoid closures
4. Do not define other functions in a function. This reduces many unexpected closure memory leaks.
5. More and smaller Functions

Although V8 JIT is a powerful engine, its smaller and more streamlined functions will be better integrated with V8. Further, if our functions are small and exquisite (about 100 lines), we will also thank ourselves for reading and maintaining our own functions.

Check style by programming: maintain style consistency and use a check tool to enhance it. We use jsstyle.

Linting (code check)

The Lint tool can perform static code analysis without running and check for potential errors and risks. For example, the break statement is omitted in caseswitch. Lint is not simply equivalent to style check. It is more targeted at objective risk analysis than subjective style selection. We use javascriptlint, which contains a variety of check items.

Logging)

Long-term attention is needed for programming and coding. In particular, consider the tools used for debugging. The first step is to record valid logs. We need to identify the information to see what is important during debugging and what is used for analysis and research during runtime. We recommend that you use Bunyan, a direct Node. js log record library. The data output format is JSON. For more information, click here.

Client Server

If an application has the distributed processing capability, it will be more attractive in the market. Similar interfaces can be described using HTTP RESTFul APIs or the original tcp json. This allows developers to combine Node experience with the asynchronous network environment, and to combine the use of streams with distributed extensible systems.

Common tools:

1. restify

In short, this is a tool for building REST services. It provides excellent support for viewing and debugging, and supports both Bunyan and DTrace.

2. fast

Fast is a lightweight tool that processes JSON messages over TCP. DTrace support allows us to quickly identify the performance characteristics of server clients.

3. workflow

Workflow is built on restify to define a series of remote services and APIs. For example, error status, timeout, reconnection, and congestion handling.


In nodejs, where are the descriptions of common functions found? Such as string processing, like asubstring?

Node. js uses google v8 as the javascript engine, so as long as it is a javascript object and function supported by chrome, it is available in node. js. The api on node's website is just something new to node. So you can see the javascript reference on mozilla's website. Developer.mozilla.org/en/docs/JavaScript/Reference

How can I use nodejs to obtain data in the list?

Cheerio
Npmjs.org/package/cheerio
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.